Pages

Creating API in Python using Flask

 Before getting started with today’s blog, in which we will learn to create API in Python using Flask, we should be aware of a few basic terms that will help you understand this article flawlessly. 


What is Flask?

Flask is a popular web framework for Python. It is a small framework that gives you the basic tools you need to build a web application, such as routing and handling requests. Flask is designed to be easy to use and gives the developer more control over how the application works. Flask is a good choice for smaller, more simple projects, or for developers who want to have more control over the application architecture.


Installing Flask:

Before we can use Flask on our device, we must first install Flask and the Restful packages that go with it. After installing libraries, we have to create our server. 


Python developers can use the below code to install Flask on their device.


if __name__ == '__main__':

    app.run(debug=True, port=8000)


Along with installing libraries and creating a server, we will have to indicate the server to launch with the port where it should be launched. So, we will add the below code at the end of our app:


if __name__ == '__main__':

    app.run(debug=True, port=8000)


WIth this our server is created and we have informed the port on which it has to run. Now we will start creating API’s 


We must specify the endpoint, the method, and the function that should be executed on that endpoint when creating an API in Python using Flask. Let's look at an example using an API that simply returns the text "Hello world!"


from flask import Flask, jsonify, request,send_file


app = Flask()


@app.route('/my-first-api', method = ['GET'])


def hello():


    return "Hello world!"


In the above codes, we have defined both endpoints and the method. We have used the GET method here. If you are using any other method, then make sure to define it in place of GET. Other methods that developers can use here in place of GET are POST, PUT, and DELETE.


Passing parameters to the API:

There are times when our APIs require parameters, especially when we put a model into production. Each model input needs to correspond to a parameter in our API.


In that regard, when making the request, we can pass arguments to our Flask API. here, we have to extract it from the request first to use them in the function, which we will do using request.args.get. 

Let's understand it with an example in which we have created an API that print “Hello {name}!”.


@app.route('/my-first-api', methods = ['GET'])

def hello():


    name = request.args.get('name')


    if name is None:

        text = 'Hello!'


    else:

        text = 'Hello ' + name + '!'


    return text


In the above codes, our API is taking the name from the URL.


In the event that the parameter is left empty, the API will return "Hello!"

If the user enters something else in place of "name," the output changes, and the API will show "Hello, “Name”!" as output.


Returning different data types with Flask:

Until now, we have returned text strings and are still unaware whether we can return data or not. For you readers, I want to tell you that APIs usually return data in JSON format. 


Here is an example showing how to retrieve the previous string in JSON format. We will use the jsonify module to return data. 


@app.route('/my-first-api', methods = ['GET'])

def hello():


    name = request.args.get('name')


    if name is None:

        text = 'Hello!'


    else:

        text = 'Hello ' + name + '!'


    return jsonify({"message": text})


In a similar manner, we are able to return a dataset or another type of object. Let's take a look at an example of what it would look like to create a new endpoint that responds to GET requests by giving the iris dataset:


@app.route("/get-iris")

def get_iris():


    import pandas as pd

    url ='https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv'

    iris = pd.read_csv(url)


    return jsonify({

        "message": "Iris Dataset",

        "data": iris.to_dict()

        })


In order to send a DataFrame, we must first convert it into an object that is capable of being converted into a JSON, such as a dictionary. Only then will the DataFrame be ready for transmission. By doing this, we will have a response that looks something like this:


resp.json()


{'data': {'petal_length': {'0': 1.4, '1': 1.4, '2': 1.3, '3': 1.5, '4': 1.4, '5': 1.7, '6': 1.4, '7': 1.5, '8': 1.4, '9': 1.5, '10': 1.5, '11': 1.6, '12': 1.4, '13': 1.1, '14': 1.2, '15': 1.5, '16': 1.3, '17': 1.4, '18': 1.7, '19': 1.5, '20': 1.7, '21': 1.5, '22': 1.0, '23': 1.7, '24': 1.9, '25': 1.6, '26': 1.6, '27': 1.5, '28': 1.4, '29': 1.6, '30': 1.6, '31': 1.5, '32': 1.5, '33': 1.4, '34': 1.5, '35': 1.2, '36': 1.3, '37': 1.5, '38': 1.3, '39': 1.5, '40': 1.3, '41': 1.3, '42': 1.3, '43': 1.6, '44': 1.9, '45': 1.4, '46': 1.6, '47': 1.4, '48': 1.5, '49': 1.4, '50': 4.7, ...


Finally, is it possible to send images using an API written in Python and built with Flask? We have seen this capability in action with FastAPI, and there was no way Flask was going to be any less capable. In point of fact, the method for doing so is very similar; the only difference is that in this instance, we need to save the content within the flask itself (or whatever directory it is), and then send it using the send_file function.


@app.route("/plot-iris")

def plot_iris():


    import pandas as pd

    import matplotlib.pyplot as plt

    import os


    url ='https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/0e7a9b0a5d22642a06d3d5b9bcbad9890c8ee534/iris.csv'

    iris = pd.read_csv(url)


    plt.scatter(iris['sepal_length'], iris['sepal_width'])

    plt.savefig('flask/iris.png')


    return send_file('iris.png')


In the above coed we ae learned to return different content with python API create using Flask. Now, its time to check whether our APIs are working correctly or not.


Checking the functioning of a Flask API:

Before running a Python API that was built with Flask, we need to make certain that it is exposed on a port. This is a prerequisite for running the API. In order to accomplish this, we need to include the code that I mentioned earlier and that is listed below:


if __name__ == '__main__':

    app.run(debug=True, port=8000)


Simply executing the Python file in which the API was created is therefore all that is required for us to get the application up and running. 


Command:


python flask/main.py


This will generate a code like the following:



It is clear that our application programming interface (API) will be operating on our local host at the port that we have specified (port 8000 in this case).


Therefore, in order to test the API, all we need to do is open up our browser and navigate to the respective endpoints; alternatively, we can directly make the requests using Python:


resp.json()


{'message': 'Hello Ander!'}


The above screen shows that the API is returning the content properly.


In addition, we are able to add Swagger and OpenApi documentation to our API in Flask; however, the process of doing so will be somewhat more laborious than the process of doing so in FastAPI.


Final thoughts:

In this blog, we have learned to create an API in Python using Flask. As you can see, the process is very simple and straightforward. Flask is a popular choice among Python developers as it is a light and flexible framework for building web apps and APIs. Also, Python is a great language for building RESTful APIs. It is easy to learn and has powerful libraries. Flask makes it easy to set up endpoints, handle HTTP requests, and make responses, making it a great choice for building small to medium-sized APIs. 


By using the features of Flask and Python, developers can quickly and easily make APIs for their apps that are scalable, secure, and strong.






No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...