Develop RESTful APIs With Python And Flask Framework

Introduction

Python is widely used when it comes to IoT, Data Engineering, Machine Learning, Automation testing, and a lot more. It's very simple to use and the learning curve isn't steep. In many cases, we do need to develop APIs in Python. In this article, we are going to cover how to create simple APIs in Python using the flask framework. There are other frameworks too like Django and FastAPI, but in this article, we will cover only flask.

What is Flask?

Flask is a framework that allows developers to build RESTful APIs in python. Flask is extremely lightweight and is widely used for quick prototypes and in some cases production too. Especially when dealing with IoT, we prefer flasks over other frameworks simply because of its ease of use. In order to get started, we need to make sure that flask is installed as a python package.

To install flask, open up the terminal, and use pip package manager to download it by executing the following command.

pip install flask

Once installed, we are good to get started.

Base code

To get things started, it is extremely simple. Let's write a skeleton code and get things moving to build a hello world application in flask.

Firstly we need to import the required packages.

from flask import Flask

Then let’s initialize the Flask class and create an object called app.

app = Flask(__name__)

According to the official documentation, the parameter name is passed to let Flask know how to obtain all the necessary resources.

Then, we need to define routes. In this case, let's define a global or default route. For that, we need to use app.route decorator. This allows to bind a function to a route in the following way.

@app.route('/')
def helloWorld():

Thus, when we run this code, by default it will run whatever is mentioned in the method helloWorld as it is bound to global route.

Inside the function, we can write logic and return the data.

@app.route('/')
def hello_world():
    return "Hello World"

Finally, we simply need to call app.run() to start the application. Thus the entire code-base will be the following.

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def hello_world():
    return "Hello World"

if __name__=='__main__':
    app.run()

Once, you run this code, you will be able to browse to localhost on browser, which will simply show “Hello World”.

Now let’s add one more route to check if it works.

@app.route('/queryparams')
def paramsDemo():
    return "Demo base code"

Hit the browser with /queryparams appended at the end and you will see “Demo base code” on the browser.

Now, that we know about the base code, let's have a discussion on handling incoming data in the form of the following.

  1. Handle GET requests using query parameters
  2. Handle post requests using body parameters

GET requests handling

To define a function, that can handle incoming GET requests, we need to add a parameter to the app.route decorator.

@app.route('queryparams',methods=['GET'])

Now, inside the method, we can use the request object from flask module to get incoming data. For example, if we need to get the request URL, we need to simply use request.url

For accessing the query string, you can use request.query_string

Let’s take an example of the following request URL.

http://localhost:5000?parama=1&paramb_2

In the above URL, the entire URL is called request URL.

The part after ‘?’ is called query string

And individual paramters are called query parameters.

Thus the following is applicable.

  1. Query URL: request.url
  2. Query String: request.query_string
  3. Query Parameters: request.args.get('PARAMETER_NAME')

Let's have a look at the following code.

@app.route('/queryparams',methods=['GET'])
def paramsDemo():
    name=request.args.get('name')
    return name

In the above code, we return the query parameter whose key is name.

POST request handling

For POST, it's simple to handle incoming requests.

The data is available in request body and can be accessed using the request module as well. But before that, we need to define the decorator as post.

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

The body can be accessed by request module using request.json which returns a dict type object.

Similarly, other metadata like headers are easy to obtain by using request.headers

Note

request.headers.get(’header name’) will return None or no exception if it doesn't exist. However,

request.headers[’header name’] will result in an exception if the name doesn't exist as it returns a dictionary type object.

Thus the code to access a parameter will be the following.

@app.route('/postparams', methods=['POST'])
def postParamsDemo():
    params=request.json
    value_a=params["value_a"]
    value_b=params["value_b"]
    sumResult=sum(value_a,value_b)
    return str(sumResult)

def sum(a,b):
    return (int(a)+int(b))

In the above code, we simply accept two params and calculate the sum and return the value.

An entire implementation along with code is mentioned in the github repo.

Conclusion

Through this article, I guess you will understand a bit about how to get started with API development in flask. A video of the entire article is there on my channel. The video is also embedded below.


Recommended Free Ebook
Similar Articles