Fast API in Python


“Fast API is used for generating REST API which is used for web services. It is completely open-source and the use of this web framework is done for building various kinds of python APIs one of which is REST API which is consistent, cacheable, and stateless in behavior and creates the standards for the transfer of data required for communication between servers and clients.

In this article, we will try to focus on the subtopics of Fast API to understand it better. These subtopics include an overview of Fast API, a Comparison between the framework of Fast API and Flask, a simple program of “Hello Bit Array” using Fast API with GET and POST, building blocks of Fast API and the future scope. Let’s begin with our learning.

 


Overview of Fast API

Fast API is the web framework with extremely high performance and suitable for the modern age requirements which can prove of enormous helps in building the application programming interfaces that are APIs along with the use of Python support for versions 3.6 or higher. These APIs are built on the type hints of python’s standards. One of the specialties about Fast API is that it has its inbuilt support for the async characteristics and features that are present in python 3.6 and higher which makes its functionality extremely fast in performance.
Due to existing shortcomings in the DRF and Flask frameworks, Sebastian Ramirez had created Fast API which was further released in 2018. The tool used for the creation of Fast API includes Pydantic and starlette. Nowadays, Fast API is used for building the APIs and apps in some of the huge tech companies including Microsoft, Netflix and Uber.

 


Some of the features of Fast API are as mentioned below

Robustness – The documentation available is automated and interactive which helps in creating the production-ready code.
Extreme performance – Reading the word, Fast API we can automatically conclude that it will be very fast in its working that is where it derived its name from. Among all the frameworks available in python right now, this one is the fastest of all.
Fast coding – The increase in the speed of developing the application when made use of Fast API is approximately 200% to 300%.
Intuitive interface – The availability of vast documentation and support of the editor makes it very easy for learning the design in Fast API. Also, using its available functionalities is very easy.
Compatibility – The framework is compatible and works absolutely fine with the schema of JSON, swagger, or even called OpenAPI now and the open standards declared for the application programming interface that is APIs.
Reduction in the number of bugs  –  It is considered to be decreasing the occurrences of the bugs present in the system to around 40%.
Type hints functionality  – Conversion and data validation can be done smoothly by making the use of type hinting functionality.
Creation of plugins – Dependency injection helps in making the creation of plugins easier.


 

Comparison between the framework of Fast API and Flask

Flask is another framework available in python which is actually referred to as a microframework that has its features including authentication, caching and the Object Relation Mapping that has an extensive implementation in the building of web apps with the help of python language. This framework is as well very scalable, fast and easy.

The below table list outs the advantages of using flask and fast API.

Flask Fast API
Intuitive and easy interface for using. Exception Handling
Flexible and components can be changed at our convenience. Coding support of asynchronous nature
Availability of development server that is built-in. Validation of data
It has its applications in projects such as static websites, social networks, e-commerce systems, social media bots, etc. It has its applications in projects such as machine learning model deployment, management of internal crises and web applications where authentication, login system and account management is done.

 


Simple program of Hello Bit Array using Fast API

There are four HTTP methods also referred to as operations sometimes which include PUT, DELETE, GET and POST. In GET method, we can pass certain parameters in the query string while the POST method expects the input data in the form of a JSON input file in python. You can use any one of them depending on how much data you want to pass from client to API and how sensitive it is.

GET HTTP method

We will consider one simple example which will demonstrate the use of GET method/ operation. This will be a simple API returning the data in the JSON format and will contain “Hello Bit Array” message in it. We will create the python file named main.py which will contain the following code in it –

 

#Required libraries should be imported
from fastapi import FastAPI

#Fast API instance needs to be created
sampleBitArrayApp = FastAPI()

#Choose and create the required path operation (Here "/")
@sampleBitArrayApp.get("/")

#Function created earlier should be defined
def func():
    return {"Customized Message": "Hello Bit Array"}

 

In order to create API, we had carried out four major steps involving importing of necessary libraries, creating a new instance of Fast API, defining the operation of the path where you want your output to be seen along with HTTP method such as GET or POST and then define the function corresponding to path operation as in our case a message.
Now, to confirm if our API is working, you can enter the following command on the terminal by navigating to the directory where main.py lies.

$ uvicorn main:sampleBitArrayApp  -reload

INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [484138] using statreload
INFO: Started server process [484140]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:43896 - "GET / HTTP/1.1" 200 OK

Now, time to run on browser and check the resultant on link http://127.0.0.1:8000

 


 

POST HTTP method

Now, for a POST request, let us consider this example

from fastapi import FastAPI
from pydantic import BaseModel

sampleBitArrayApp = FastAPI()

class value_of_pages_content(BaseModel):
  Number_of_pages_for_article1:int
  Number_of_pages_for_article2:int
  Number_of_pages_for_article3:int
  Number_of_pages_for_article4:int

@sampleBitArrayApp.post('/show_content')
def show_content(content: value_of_pages_content):
  return({"content":[content.Number_of_pages_for_article1,content.Number_of_pages_for_article2,content.Number_of_pages_for_article3,content.Number_of_pages_for_article4]})

 

When we go for accessing the URL http://127.0.0.1/show_content.

We get following output in the response content when we pass respective values for Number_of_pages_for_article1, Number_of_pages_for_article2, Number_of_pages_for_article3 and Number_of_pages_for_article4 –

$curl http://127.0.0.1:8000/show_content -X POST -d '{"Number_of_pages_for_article1":1, "Number_of_pages_for_article2":2, "Number_of_pages_for_article3":3,"Number_of_pages_for_article4":4}' -H "Content-Type: application/json"

{"content":[1,2,3,4]}

 

Building blocks of Fast API
Some of the most important concepts when learning Fast API include request body, query parameters and path parameters. Let’s have a detailed discussion on it.

Request body
It’s is the data that is supposed to be transferred from the client to the target API you are creating. Pydantic models are used in fast API to inculcate this. Let us consider one example to understand how it can be done

 

from typing import Optional
from pydantic import BaseModel
from fastapi import FastAPI 

class Article(BaseModel):
    topic: str
    definition: Optional[str] = None
    numberOfWords: int
    writer: Optional[str] = None
 
sampleBitArrayApp = FastAPI()

@sampleBitArrayApp.post(“/articles/”)
def create_article(article: Article):
    return article

 

In the above example, we first imported the packages that were required, and then the request data model that we will be using was declared. Further, we went for creating a new instance of the class of FastAPI that we have created and POST path is created to which we will be adding our newly created request model.
The output of the above program is –

 

$ curl http://127.0.0.1:8000/articles/ -X POST -d '{"topic":"FastAPI in python","definition":"Features - how to use","numberOfWords":1010, "writer": "Bitarray_user"}' -H "Content-Type: application/json" 2>/dev/null|jq
{
  "topic": "FastAPI in python",
  "defination": null,
  "numberOfWords": 1010,
  "writer": "Bitarray_user"
}

 


 

Query parameters
These are optional in nature and when the declaration of path parameters is not done for functional parameters than by default they are treated as the query parameters.

Let us have one example to get insights –

from fastapi import FastAPI
 
sampleBitarrayApp = FastAPI()
 
article_topics = [{"article_topic": "Redis"}, {"article_topic": "Fast API"}, {"article_topic": "PostgreSQL"}]
 
@sampleBitarrayApp.get("/articles/")
def read_articles(begin: int, stop: int):
    return article_topics[begin : begin + stop]

The query parameters are present in the link after the presence of “?” which acts as a separator. All the query parameters are in the format of key-value pairs and are separated among themselves by using an ampersand & symbol. The query parameters in the above URL  begin which has the value of 0 and stop with 10 as its value.

output:

$ curl "http://127.0.0.1:8000/articles/?begin=0&stop=3" 2>/dev/null|jq
[
  {
    "article_topic": "Redis"
  },
  {
    "article_topic": "Fast API"
  },
  {
    "article_topic": "PostgreSQL"
  }
]

 


 

Path parameters

We can make the scop of the API to a single source by using the path parameters in it which in turn results in permission that nobody is needed to create when building resource finder or similar API. All the path parameters are enclosed inside the curly parenthesis that are {} as it helps in controlling the aspect of representation done for the particular resources. The position of path parameters is present before the query string and end till the endpoint. An example related to the same is

from fastapi import FastAPI
 
sampleBitarrayApp = FastAPI()
 
@sampleBitarrayApp.get("/articles/{article_topic}")
def read_article(article_topic):
  return {"article_topic": article_topic}

Here the article_topic is the path parameter which is further passed to the function of read_articles as an argument.

Output:

curl "http://127.0.0.1:8000/articles/3"
{"article_topic":"3"}

 

+ There are no comments

Add yours