13 minutes read

Previously, we've already discussed what REST API architecture is, its main principles, and the basic HTTP methods. In this topic, we are going to discuss how REST can be incorporated into Flask. It will allow us to follow REST principles when creating Flask applications.

Flask-RESTful

Let's start with a Flask extension called Flask-RESTful. It is a Python module that allows us to build a RESTful API with Flask. Before we go further, we should note that all API endpoints (routes) will look like the default view functions.

The first thing we need is the Api class initialized by connecting a specific application. It maintains all API, including endpoints (routes), different requests, and so on. Let's take a look:

from flask import Flask
from flask_restful import Resource, Api

app = Flask('main')
api = Api(app)

There, we create the default application and initialize the Api object that helps us with the RESTful part of our project.

The second thing we need is Resource. It's a class that provides an easy way to create API functions: we can write classes that inherit Resource and use its architecture to create an API. In the example below, we create the HelloWorld class that inherits Resource with a GET method. This view class will be an API endpoint:

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

As you may have guessed, the names of class functions define the HTTP request method that this function will handle. In this way, we have indicated the API behavior when we access this endpoint with the GET method.

Finally, we need to indicate which URL will access our endpoint. You can do this with the add_resource method:

api.add_resource(HelloWorld, '/')

app.run(debug=True)

Time to run our app! Let's look at what we've created and send a couple of requests. If everything is correct, we will see the following string when we try to reach https://127.0.0.1:5000/:

a couple of requests

This API behavior allows us to create Resource objects instead of view functions. What are the pros of this? It's easier to use the pre-defined methods than divide the request types with the request object.

Parsing arguments

Flask allows us to quickly get data from the request body, but we should also parse arguments from a URL for our API. The reqparse interface can help us with this! It's a built-in flask_restful feature that works similarly to the argparse module.

Again, we start with the default app and create the Api object for it.

from flask import Flask
from flask_restful import Resource, Api, reqparse

app = Flask('main')
api = Api(app)

Don't forget to preconfigure the parser:

parser = reqparse.RequestParser()
parser.add_argument('Writing', type=str, help='This is what You will see on The Wall')

We've created the RequestParser object and specified an argument with the name of writing, type is str, a description is provided in the help argument. The next step is to create a resource that requires data from a URL:

class HelloArgs(Resource):
    def get(self):
       data = parser.parse_args()  
       return {'data_from_url': data}

The final move — create a route to our resource using the add_resource method:

api.add_resource(HelloArgs, '/')

This is it! Let's start the application and see what happens. To test our API, we will use curl and execute the following command:

curl 127.0.0.1:5000/?Writing=PinkFloyd

As you know, we write a question mark in URL requests to denote the URL end and the start of arguments. We send a request to the URL 127.0.0.1:5000/ and specify the writing argument.

As we've mentioned above, reqparse is similar to argparse. It allows you to parse the query request string easily and typecast its parameters. If we take the example above, we will end up with the following result:

{"data_from_url": {"Writing": "PinkFloyd"}}

Another way to get data from a URL is to use the basic Flask views. You can also use it with flask_restful. We can put the variable name directly to the URL. It will be like this (you can imagine any variable instead of megavar):

http://127.0.0.1:5000/data/<megavar>

After this, insert this URL in the corresponding Python function:

@app.route('/data/<megavar>')
def main_view(megavar):
    return f'Your data from URL: {megavar}'

We can use both ways to get data from the users or another program; the choice depends on the situation.

Getting JSON data from requests

As you may already know, REST applications often use JSON as a body data exchange format, so it's essential to know how to extract this data from client requests.

Flask's request object has a json attribute that returns the request's JSON body if it has one. If the request data's MIME-type differs from application/json, it will return None.

As a rule, Input JSON data is received via POST request; assuming you have created an app in the previous paragraph, let's add the Hello Resource and a POST endpoint to it and see how retrieving JSON works:

from flask import request

class Hello(Resource):
    def post(self):
        # let's assume we're expecting to receive a JSON body
        # containing key 'message'
        data = request.json
        message = data['message']
        return {"response": "message received"}

The json attribute returns a regular Python dict with all the JSON data received from the client. So if the request body was {"message": "Hello world"}; then in the example above the message variable will be set to store the string value — Hello world.

Conclusion

In this topic, we've learned how to create simple RESTful APIs and to parse arguments with Flask tools. The flask_restful extension is practical when it comes to building REST APIs. It provides you with multiple tools to create API endpoints with ease. Now, let's practice!

21 learners liked this piece of theory. 4 didn't like it. What about you?
Report a typo