Retrieve another resource from the Flask API

I have developed a basic Flask API that returns a list of strings. Here is the code:

from flask import Flask, request
from flask_restful import Resource, Api
from json import dumps

app = Flask(__name__)
api = Api(app)

class Product(Resource):
    def get(self):
        return {'products':['A','B','C','D','E','F','G','H','I','J','K']}

class Accounting(Resource):
    def get(self):
        return {'accounting':['1','2','3','4','5','6','7','8','9']}

api.add_resource(Product, '/')
api.add_resource(Accounting, '/')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)

By using the provided PHP code snippet, I can successfully access and display the contents of the "product" resource.

<?php
        $json = file_get_contents('http://product-service/');
        $obj = json_decode($json);
        $products = $obj->products;
        echo "$products[0]";
?>

However, I am encountering issues in accessing the second resource called "accounting". Even when trying to access it directly through the home address or with PHP code, the resources are not visible or reachable.

<?php
        $json = file_get_contents('http://product-service/');
        $obj = json_decode($json);
        $accounts = $obj->accounting;
        echo "$accounts[0]";
?>

If anyone could provide guidance on how to resolve this issue, I would greatly appreciate it.

Thank you for your assistance.

Sincerely, Michael

Answer №1

When setting up your APIs, it's important to organize them efficiently. Instead of combining both products and accounting under one route "/", consider separating them into distinct API endpoints:

from flask import Flask, request
from flask_restful import Resource, Api
from json import dumps

app = Flask(__name__)
api = Api(app)

class Product(Resource):
    def get(self):
        return {'products':['Apple','Banana','Carrot','Date']}

class Accounting(Resource):
    def get(self):
        return {'accounting':['101','202','303','404']}

api.add_resource(Product, '/products')
api.add_resource(Accounting, '/accounting')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting object to string does not yield the desired outcome

I am working with Selenium in Python and I am encountering an issue when trying to convert the result of name = browser.find_element_by_css_selector('elementname') into a string. The output is 'WebElement' instead of the actual eleme ...

Grab the information swiftly

When running a presto command, I received the following result: a| b| c --+--+------ 1 | 3| 6 2 | 4| 5 I am aware of cursor.fetchall() to retrieve all data and cursor.fetchone() for a single row. Now, I am interested in extracting data from a sp ...

Executing Python code through a website using PHP - is there a way to deactivate the button once it has been clicked?

Can you assist with the following issue? <?php if(isset($_POST['MEASURE'])) { shell_exec("sudo python /var/www/html/lab/mkdir.py"); } ?> Here is the HTML part: <form method="post" > <input type="submi ...

I'm having trouble retrieving the episode ids using imdbpy

I am new to Python and currently working on fetching movie information using Imdbpy. The code snippet I have written is as follows: ia = IMDb() results = ia.search_movie(movie_name) movie_id = results[0].getID() movie = ia.get_movie(movie_id) If the movie ...

As Pool.map is utilized with Python's multiprocessing, the program gradually slows down

Have you ever wondered Why does a Python multiprocessing script slow down after a while? Below is a code snippet that utilizes Pool: from multiprocessing import Pool Pool(processes=6).map(some_func, array) Unfortunately, the program slows down after a fe ...

Recommendation for a web service Python framework

In the process of developing a web service that will facilitate file upload/download, user management, and permissions, I am seeking guidance on which web framework to utilize for this task. This service will essentially function as remote storage for med ...

Tips for combining cells partially in a vertical direction within the pandas library

Here is the dataframe I am working with: index Flag Data 0 1 aaaa 1 0 bbbb 2 0 cccc 3 0 dddd 4 1 eeee 5 0 ffff 6 1 gggg 7 1 hhhh 8 1 iiii I want to obtain a merged vertical data where it's divided by Flag 1. index Flag Dat ...

Ways to determine the version of the Selenium RC server

I am currently utilizing selenium2 RC along with the python client (selenium.py) and I am in search of a way to retrieve the version of the selenium installed on the server. Can anyone advise if there is a command that can be sent to the server to fetch ...

Python: The best method to divide a sentence into approximately equal sections

I've been attempting to develop a function that can divide a sentence into n lines, aiming for as even of distribution as possible. However, I'm encountering issues where either the first or last line ends up significantly longer than the rest. ...

Modify each item/entry within a 90-gigabyte JSON file (not necessarily employing Python)

I'm facing a challenge with a massive 90G JSON file containing numerous items. Here's a snippet of just three lines for reference: {"description":"id1","payload":{"cleared":"2020-01-31T10:23:54Z","first":"2020-01-31T01:29:23Z","timestamp":"2020- ...

Selenium in Python failing to check the checkbox

Why am I encountering difficulty in selecting the checkbox on the webpage using Selenium with Python? import traceback import selenium.webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ...

Utilizing Scrapy for Extracting Size Information obscured by Ajax Requests

I am currently trying to extract information about the sizes available for a specific product from this URL: However, I am encountering difficulty in locating the details hidden within the Select Size Dropdown on the webpage (e.g., 7 - In Stock, 7.5 - In ...

Enhancing logging format with additional dictionary containing optional components

I am trying to replicate this specific outcome: # code logging.basicConfig(format='%(levelname)s: %(sublevel) %(message)s', level=logging.DEBUG) logging.debug("abc", extra={'sublevel':2}) logging.debug("def", extr ...

Python does not support serialization of JSON data

Having a collection of objects in the specific structure shown below, I aimed to store it in a json file. {'result': [{'topleft': {'y': 103, 'x': 187}, 'confidence': 0.833129, 'bottomright': {&ap ...

Comparing time across different time zones using Python

I need to schedule daily emails for users at 7am in their respective time zones. For instance, User 1 is in the America/Los_Angeles time zone, while Customer 2 is in America/New_York and would receive the email at 7am their local time, but it would be 4am ...

What is the best way to compress or combine a pandas dataframe vertically?

My dataset consists of a pandas dataframe with multiple columns, but for now let's only examine two: df = pd.DataFrame([['hey how are you', 'fine thanks',1], ['good to know', 'yes, and you' ...

Can Python mechanize navigate through links based on URLs and detect the value of the nr parameter?

Apologies for having to pose such a question, but I am finding that the documentation for python's mechanize is quite lacking. Despite my efforts, I cannot seem to figure this out. The only example I could locate for following a link is as follows: r ...

Load workbook 'a' in read-only mode using openpyxl to access data from an Excel file that is currently open in Windows

My current task involves loading a workbook and extracting its data with openpyxl on a Windows system. I am facing the challenge of needing to access the workbook even when it is already opened in Excel. Despite using load_workbook(filename=filename, read ...

Can Selenium handle gathering multiple URLs at once?

Looking to create a Smoke test for a list of URLs by checking their titles for validity. Is this achievable? class identity(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() driver = self.driver self.driver.implicitly_wait(30) @da ...

Update a class from a separate module in Python using monkey patching

I have a class named bar in module A. class bar(): def __init__(item1, item2): self.item1 = item1 self.item2 = var2 def method_a(self): pass def method_b(self): pass bar_ = bar("examp ...