Flask-RESTful API: multiple and complex endpoints

46,871

Solution 1

Your are making two mistakes.

First, Flask-RESTful leads you to think that a resource is implemented with a single URL. In reality, you can have many different URLs that return resources of the same type. In Flask-RESTful you will need to create a different Resource subclass for each URL, but conceptually those URLs belong to the same resource. Note that you have, in fact, created two instances per resource already to handle the list and the individual requests.

The second mistake that you are making is that you expect the client to know all the URLs in your API. This is not a good way to build APIs, ideally the client only knows a few top-level URLs and then discovers the rest from data in the responses from the top-level ones.

In your API you may want to expose the /api/users and /api/cities as top-level APIs. The URLs to individual cities and users will be included in the responses. For example, if I invoke http://example.com/api/users to get the list of users I may get this response:

{
    "users": [ 
        {
            "url": "http://example.com/api/user/1",
            "name": "John Smith",
            "city": "http://example.com/api/city/35"
        },
        {
            "url": "http://example.com/api/user/2",
            "name": "Susan Jones",
            "city": "http://example.com/api/city/2"
        }
    ]
}

Note that the JSON representation of a user includes the URL for that user, and also the URL for the city. The client does not need to know how to build these, because they are given to it.

Getting cities by their name

The URL for a city is /api/city/<id>, and the URL to get the complete list of cities is /api/cities, as you have it defined.

If you also need to search for cities by their name you can extend the "cities" endpoint to do that. For example, you could have URLs in the form /api/cities/<name> return the list of cities that match the search term given as <name>.

With Flask-RESTful you will need to define a new Resource subclass for that, for example:

    class CitiesByNameAPI(Resource):
        def __init__(self):
            # ...    
        def get(self, name):
            # ...

    api.add_resource(CitiesByNameAPI, '/api/cities/<name>', endpoint = 'cities_by_name')

Getting all the users that belong to a city

When the client asks for a city it should get a response that includes a URL to get the users in that city. For example, let's say that from the /api/users response above I want to find out about the city of the first user. So now I send a request to http://example/api/city/35, and I get back the following JSON response:

{
    "url": "http://example.com/api/city/35",
    "name": "San Francisco",
    "users": "http://example/com/api/city/35/users"
}

Now I have the city, and that gave me a URL that I can use to get all the users in that city.

Note that it does not matter that your URLs are ugly or hard to construct, because the client never needs to build most of these from scratch, it just gets them from the server. This also enables you to change the format of the URLs in the future.

To implement the URL that gets users by city you add yet another Resource subclass:

    class UsersByCityAPI(Resource):
        def __init__(self):
            # ...    
        def get(self, id):
            # ...

    api.add_resource(UsersByCityAPI, '/api/cities/<int:id>/users', endpoint = 'users_by_city')

I hope this helps!

Solution 2

you can do the id/name thing without duplicating the resource:

api.add_resource(CitiesByNameAPI, '/api/cities/<name_or_id>', endpoint = 'cities_by_name')

class CitiesByNameAPI(Resource):
    def get(self, name_or_id):
        if name_or_id.isdigit():
            city = CityModel.find_by_id(name_or_id)
        else:
            city = CityModel.find_by_name(name_or_id)

        if city:
            return city.to_json(), 200
        return {'error': 'not found'}, 404

not sure if there are any negative effects from this.

Share:
46,871
Alex Chumbley
Author by

Alex Chumbley

I am currently a computer science student. I just like learning new stuff, this seems like the right place to be. Thanks to everyone that makes this such a good community.

Updated on July 09, 2022

Comments

  • Alex Chumbley
    Alex Chumbley almost 2 years

    In my Flask-RESTful API, imagine I have two objects, users and cities. It is a 1-to-many relationship. Now when I create my API and add resources to it, all I can seem to do is map very easy and general URLs to them. Here is the code (with useless stuff not included):

    class UserAPI(Resource):  # The API class that handles a single user
      def __init__(self):
        # Initialize
    
      def get(self, id):
        # GET requests
    
      def put(self, id):
        # PUT requests
    
      def delete(self, id):
        # DELETE requests
    
    class UserListAPI(Resource):  # The API class that handles the whole group of Users
      def __init__(self):
    
      def get(self):
    
      def post(self):
    
    api.add_resource(UserAPI, '/api/user/<int:id>', endpoint='user')
    api.add_resource(UserListAPI, '/api/users/', endpoint='users')
    
    class CityAPI(Resource):
      def __init__(self):
    
      def get(self, id):
    
      def put(self, id):
    
      def delete(self, id):
    
    class CityListAPI(Resource):
      def __init__(self):
    
      def get(self):
    
      def post(self):
    
    api.add_resource(CityListAPI, '/api/cities/', endpoint='cities')
    api.add_resource(CityAPI, '/api/city/<int:id>', endpoint='city')
    

    As you can see, I can do everything I want to implement a very basic functionality. I can GET, POST, PUT, and DELETE both objects. However, my goal is two-fold:

    (1) To be able to request with other parameters like city name instead of just city id. It would look something like:
    api.add_resource(CityAPI, '/api/city/<string:name>', endpoint='city')
    except it wouldn't throw me this error:

    AssertionError: View function mapping is overwriting an existing endpoint function

    (2) To be able to combine the two Resources in a Request. Say I wanted to get all the users associated with some city. In REST URLs, it should look something like:
    /api/cities/<int:id>/users

    How do I do that with Flask? What endpoint do I map it to?

    Basically, I'm looking for ways to take my API from basic to useful.

  • Alex Chumbley
    Alex Chumbley over 10 years
    Wonderful, thanks for the fixes. Also thanks for the suggestion of hiding most of my API
  • Mark Hildreth
    Mark Hildreth over 10 years
    While Miguel is pretty much entirely correct, I think it's important to point out that "[Expecting the client to know all of the URLs in your API] is not a good way to build APIs" is simply one opinion on the matter. Defining the URLs up front is not going to cause a syntax error, nor will it cause the application to crash; it is a design decision. Whether it is better to go with a defined list of URLs, or just a top-level API with URLs to the sub-level of the API (or some other solution) is still up for debate, and the correct answer may still be project-specific.
  • Miguel Grinberg
    Miguel Grinberg over 10 years
    @MarkHildreth: Agreed.
  • Alex Chumbley
    Alex Chumbley over 10 years
    Interesting take on the subject. Would you think that the fact that only I am planning on using this API makes a difference? So, if this API is made for use in a Mobile App that I don't plan on exposing to other people, that means that I can expose all of my URLs safely?
  • Miguel Grinberg
    Miguel Grinberg over 10 years
    Exposing APIs or not is not a safety/security issue, it's a matter of encapsulation. The more you make public the less you'll be able to change in the future. Also, it's more work for the client to have to build URLs from IDs, versus building the URLs in the server with url_for() and passing them to the client ready to be used.