fbpx
Flask RestAPI - Technology vector created by freepik

Flask RestAPI – Python

Read Time:7 Minute, 7 Second

Python is a great programming language. It is used for machine learning, artificial intelligence, big data, and more. Another use for Python is developing a backend using Flask. In this guide, we will explore some of Flask’s capabilities and will build a simple Flask RestAPI.

What is Flask

Simply put, Flask lets you use Python for the back-end. This means you will have all of Python’s capabilities on your back-end. Whether to use Flask for your back-end or not, depends on your requirement and what you are trying to acomplish.

ProblemSolver is a web development consultant and they can also help you build and develop your idea into a product.

Here is Flask’s description from the Python packages index:

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Flask offers suggestions, but doesn’t enforce any dependencies or project layout. It is up to the developer to choose the tools and libraries they want to use. There are many extensions provided by the community that make adding new functionality easy.

Setting up Flask

We are going to assume you already have your Python environment set up. We are using JetBrains’ PyCharm Community. To use Flask, we first need to install the package.

Open a terminal and navigate it to your project’s root folder. Then, run the following command:

pip install Flask

Now, let’s write Flask’s hello world program and understand it.

Flask – “Hello, world!”

First, to use Flask, we need to import it. Import Flask using the following command:

from flask import Flask

We need to store our Flask application in a variable so we can reference it later. Add the following code to do that and to initialize the Flask application:

app = Flask(__name__)

As mentioned before, flask lets us create a backend using Python. This means we are accessing Flask using a URL. Flask uses function decorations to map what function will be triggered when accessing the Flask application using the URL.

Add the following code to map a function to the domain’s root and return “Hello, world!” when accessing it:

@app.route('/')
def index():
    return 'Hello, world!'

Finally, let’s tell out application its host and the port used to access our backend aaplication:

app.run(host='0.0.0.0', port=5000)

This will run the program on localhost and will direct all traffic from port 5000 to our Flask application.

Here is the complete “hello world” application’s code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, world!'

app.run(host='0.0.0.0', port=5000)

Run the program and open http://localhost:5000. Nice, we have created our “Hello, world” Flask application. Now let’s expand our application by adding some endpoints and functionality to it.

Flask RestAPI

Though we are not going to do anything too complicated, we want to explain Flask’s basics so you can then go ahead and build more complicated applications.

Flask RestAPI – Path Parameter(s)

There are multiple types of parameters in a request. There are query string parameters, path parameters, request body parameters, and header parameters. As referred to in the title, in this section we will explain how to get path parameters in our Flask RestAPI application.

Create a new endpoint in our Flask application. Add the following line under the index function from earlier:

@app.route('/parameter')
def url_parameter():
    return "This is your path parameter: "

This will create a new endpoint in our application that is accessible from the URL “http://localhost:5000/parameter”. Rerun your application and access that URL. Now that we have the new endpoint working and accessible, let’s add the path parameter to it.
Change the above code to this:

@app.route('/parameter/<some_parameter>')
def url_parameter(some_parameter):
    return "This is your URL parameter: " + some_parameter

Let’s break it down.

@app.route('/parameter/<some_parameter>')

Adding the “<some_parameter>” tells Flask to expect a path parameter after the “/parameter/” part of the URL and its reference name in the code will be “some_parameter”.

def url_parameter(some_parameter):

This tells the Flask application to use the parameter given in the URL path. Notice, that the function parameter should be the same as the value inside <>.

    return "This is your URL parameter: " + some_parameter

We are then printing the parameter back.

Up to this point, your code should look like that:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, world!'


@app.route('/parameter/<some_parameter>')
def url_parameter(some_parameter):
    return "This is your path parameter: " + some_parameter

app.run(host='0.0.0.0', port=5000)

Run the application and open http://localhost:5000/parameter/Hello

Here is an example for getting two path parameters in a single request (notice the “another_parameter”):

from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, world!'


@app.route('/parameter/<some_parameter>/<another_parameter>')
def url_parameter(some_parameter, another_parameter):
    return ("This is your path parameters are: %s, %s" % (some_parameter, another_parameter))

app.run(host='0.0.0.0', port=5000)

Flask RestAPI – Query Parameters

In the previous section, we used Flask to retrieve a path parameter. Now we will see how we can retrieve the request’s query parameters. The first thing we need to do is to add an import. Import ‘request’ from Flask. We can do this by changing our already existing import to the following.

from flask import Flask, request

Now, Let’s define a new endpoint add retrieve the query parameters.

@app.route('/query_params')
def query_parameter():
    data = request.args
    return data

app.run(host='0.0.0.0', port=5000)

Go to http://localhost:5000/query_params?test_param=Hello, world! and viola, you can see we are successfully retrieving (and printing) the quest parameters.

We can access the query parameters using the ‘request.args’ field.

Flask RestAPI – Body Parameters

Now that we know how to retrieve path parameters and query parameters, let’s learn how to retrieve body parameters. To add body parameters, you will need to use software such as Postman.

The body parameters are retrieved in a similar way to the query parameters. The difference is in the field it is stored in. To retrieve the query parameters, we have used ‘request.args’. To retrieve the body parameters, we will use ‘request.data’.

Here is an example code:

@app.route('/body_params')
def body_parameters():
    data = request.data
    return data

Here is everything we wrote up until now:

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/')
def index():
    return 'Hello, world!'


@app.route('/parameter/<some_parameter>/<another_parameter>')
def url_parameter(some_parameter, another_parameter):
    return ("This is your path parameters are: %s, %s" % (some_parameter, another_parameter))


@app.route('/query_params')
def query_parameter():
    data = request.args
    return data


@app.route('/body_params')
def body_parameters():
    data = request.data
    return data

app.run(host='0.0.0.0', port=5000)

Flask RestAPI – Methods

There is all kind of request methods while the most used are GET and POST.
In Flask, the default method is GET. Since we did not tell Flask to use a different method in our previous declared endpoints, they all require the requests to use the GET method. If you will try to access our endpoints using a different method (again, you can do so using software like Postman), Flask will serve an error.

To use a different method, simply add the ‘methods’ parameter to the app. route function decoration.
Here is an example using the last endpoint we have created (body_params):

@app.route('/body_params', methods=["POST"])

Here is an example to assign more than one method for a single endpoint:

@app.route('/body_params', methods=["GET", "POST"])
def body_parameters():
    data = request.data
    return data

Conclusion

There is a lot more Flask can do but this is what we chose to cover in this guide.
Let us know in the comments below if you are looking for another guide and we just might write it.
Check our other guides 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *