Pages

Creating an API in Python with FastAPI

 APIs are the most crucial element of any mobile application that allows devices to interact with each other to exchange information. There is an API behind every task that we perform on a mobile application, whether it's just sending a normal message to a close friend or a formal email to an MNC. 


When working with Python, we have to make a number of APIs that improve the way our web app works and make it available to more people. Through a standard protocol like HTTP, these APIs give access to certain data, services, or features of our application.


In our previous blogs, we have learned to design a basic mobile app in Python using the Kivy Framework and deploy it on different platforms. Also, we have learned to create APIs in Python using the Flask framework. So, it's time to move forward and learn to create APIs with other frameworks. 


In today's blog, we'll talk about the basics of using frameworks like FastAPI to make an API in Python. You'll learn about RESTful API design, the different ways to send and receive data (like GET, POST, PUT, and DELETE), and how to use authentication and authorization to keep your API safe.


Additionally, we'll cover how to test your API to make sure it's functioning as expected and how to deploy it to a production environment. By the end of this blog, you'll have a solid understanding of how to build and deploy a basic API in Python. However, to have comprehensive knowledge, it is important to learn the basics of API.


What is an API?

An API (Application Programming Interface) is a set of protocols, routines, and tools for building software and applications. An API defines how software components should interact and APIs allow for communication between different systems and applications. They provide a way for applications to request services or data from an operating system, library, or another application, and to receive a response.


API's Function in a Mobile Application

APIs are very important to the development of mobile apps because they let them talk to other services or data sources. By using APIs, mobile apps can get or change data from other places, like databases, cloud services, or other websites, without having to access the code that runs underneath. This results in faster, more efficient, and more flexible mobile applications.


APIs also let mobile apps talk to each other, which means they can share data, features, or services with each other. Lets understand it better with an example: Aweather app can use an API provided by a weather service to retrieve the latest weather information and display it to the user.


In addition, APIs can also help to secure mobile applications by handling sensitive data, such as user information, in a secure and controlled manner. By using APIs, the actual data can be stored in a secure location and only accessed through a secure channel, reducing the risk of data breaches. As a result, whether you are developing a simple application to provide your service globally or a financial app, it is critical to install an API. 


Main components of an API: 

  1. Endpoints: A specific URL that represents a specific resource or collection of resources. An API usually has several endpoints that represent different resources, and each endpoint typically has a specific purpose.


  1. Requests: A request is sent by the client to the API, asking for data or to perform some action. The request typically contains information about the endpoint being accessed, the method being used (e.g., GET, POST, PUT, DELETE), and any data or parameters being passed.


  1. Responses: A response is sent by the API to the client in response to a request. The response typically contains data or information requested in the request, or a status code indicating the success or failure of the request.


  1. Methods: The methods define the type of action that the client wants to perform on the resource. Common methods include GET, POST, PUT, and DELETE.


  1. Authentication: APIs often require authentication, which is the process of verifying the identity of the client making the request. This is typically done using API keys or OAuth tokens.


  1. Authorization: After authentication, authorization determines what actions a client is allowed to perform on a resource. This is usually controlled through access controls and permissions.


  1. Documentation: APIs usually come with documentation that explains how to use the API, including information on endpoints, methods, parameters, and response codes.


These are the main components of an API, but the specifics can vary depending on the type of API and the needs of the application.


How can we create an API in Python with FastAPI?

There are different frameworks using which we can create API for python and FastAPI is one among them.  


What is FastAPI?

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python-type hints. It is built on top of Starlette for the web parts, and Pydantic for the data parts. It includes features such as easy and fast route definition, request validation using Python type annotations, automatic documentation using the OpenAPI standard, and asynchronous support.


Requirements:

Step 1: install Fastapi and uvicorn

Before heading further it is important to install Fastapi and uvicorn on your device. Use the below command to install both libraries


pip install fastapi

pip install uvicorn


Step 2: Define API

The only thing left to do is to create a Python file where we will define our API now that the packages have been installed. We must create an app in this file that contains the APIs, along with their endpoints, parameters, etc.


Once the app is ready, that is where we define the data the API needs, including the endpoint, HTTP method, input arguments, and what the API will do behind the scenes.


from fastapi import FastAPI

app = FastAPI()


@app.get("/my-first-api")

def hello():

  return {"Hello world!"}


This would result in the creation of a very basic API that simply returns "Hello world!". As you can see, we have defined the method (get), the endpoint ("/"), and the function that should be executed by this API in just a few lines.


We even have the option of passing arguments to our API for it to use in the function that it performs. When we send a piece of data to one of our functions as an argument, we are obligated to specify what kind of data it is (a number, a string, etc.).


Let’s see it with the help of an example:


from fastapi import FastAPI

app =from fastapi import FastAPI

app = FastAPI()


@app.get("/my-first-api")

def hello(name: str):

  return {'Hello ' + name + '!'


Now, in order for this API to function properly when we make a request to it, we will be required to supply it with the name parameter. That is to say, whereas in the past it was sufficient for us to go to http://127.0.0.1:8000/my-first-api, from now on we will be required to pass the name parameter. The request will appear as follows as a result:


http://127.0.0.1:8000/my-first-api?name=Ander


This argument is required because we have included the name argument; if it is not included in the request, the request will not be successful. Nevertheless, it's possible that we'll want to pass some optional arguments.


In order to accomplish this, we need to specify that the argument is None, and FastAPI will interpret it in the appropriate manner. Example: we are going to create an API to which you will have the option to either pass or not pass the name of the variable. If you pass it, it will return "Hello name>!," and if you don't, it will just return "Hello!"


from fastapi import FastAPI


app = FastAPI()


@app.get("/my-first-api")

def hello(name = None):


    if name is None:

        text = 'Hello!'


    else:

        text = 'Hello ' + name + '!'


    return text


Return different data types with FastAPI

Although the vast majority of the time an API will return text (a prediction, data, etc.), there are many instances in which it will return other types of data. For example, it may return an image or a DataFrame.


In the case of "normal" objects, such as a DataFrame, FastAPI will convert the object in question to a JSON file straight away.


from fastapi import FastAPI


app = FastAPI()


@app.get("/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 iris


In this case, the application that uses our FastAPI will look like this:


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

def plot_iris():


    import pandas as pd

    import matplotlib.pyplot as plt


    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('iris.png')

    file = open('iris.png', mode="rb")


    return StreamingResponse(file, media_type="image/png")


Checking operation of a FastAPI API

As I mentioned at the beginning of this section, in order for us to create an API in FastAPI, we need to include our code in a Python file, and main.py is the file that is recommended. In addition to that, the installation of uvicorn is required. Taking all of this into consideration, we are able to put our API to work in a very straightforward manner by using the code that follows:


uvicorn main:app --reload


This will allow our application to run and give us access to our API in the browser as well as via local calls. The API is only available on the local machine for the time being, as it has not been published online. Either http://127.0.0.1/ or http://localhost/ will work, but they must be accessed through the same port as the API. The simplest way to find out is to click on the link provided by uvicorn when the API is called:



Let's see how we can put it into practice by requesting an API with all the endpoints I've described so far. 



import requests

from PIL import Image

import io


resp = requests.get('http://127.0.0.1:8000/plot-iris')

file = io.BytesIO(resp.content)

im = Image.open(file)

im.show()


It is clear that the image is being returned to us by our API in the correct format. Let's put the first endpoint that we've created to the test right now:


resp = requests.get('http://127.0.0.1:8000/my-first-api?name=Ander')

resp.text


'"Hello Ander!"'


As can be seen, the process of developing an API with the help of FastAPI is extremely uncomplicated, lightning-fast, and user-friendly. However, FastAPI is not the only method available for developing an API using Python. Flask is another method that can be used to accomplish this. You can check the steps to create API in python using flask from our previous blog. 


Final Thoughts: FastAPI is a modern and fast Python framework for building APIs. It has several features that make it a good choice for building efficient and scalable APIs, such as asynchronous support, type annotations, and automatic documentation. With its user-friendly API and easy-to-read syntax, developers can quickly build and deploy their API, allowing them to focus on the core business logic of their application. Additionally, the robust ecosystem of libraries and tools that work with FastAPI makes it an even more attractive choice for developing APIs in Python.




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...