FastAPI is a modern API framework in python. This is one of the latest API framework which is way faster than other web api frameworks such as Flask and Tornado. I have developed several web applications using Flask and Tornado. So my views will be mostly based on a comparison between these frameworks and FastAPI.

The following are some of my observations about FastAPI.

  • Very easy to learn the framework and develop the code
  • API documents will get generated automatically without any extra lines of code and additional effort. Swagger UI and redoc gets generated automatically.
  • Easy to convert the code from Flask to FastAPI
  • The framework is production ready and it is widely used in industry.
  • Easy to build large scale web applications with multiple micro services using routers.
  • Faster performance compared to other frameworks
  • Works on the Python version greater than 3.6
  • FastAPI validates the data that reaches the API

A sample FastAPI based application is given below.

Requirements

FastAPI works on python versions above 3.6

Installation

The following packages need to be installed to develop and run a fastapi application. The first package is the fastapi package and the second one is the ASGI server for deploying the application in production. Flask framework uses WSGI server such as gunicorn

pip install fastapi
pip install uvicorn[standard]

The above packages works well on Windows as well as Linux OS. Once the packages are installed, we can develop a sample API using FastAPI. Let us develop a module with the name fast_api_sample.py

from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def my_first_get_api():
"""
Sample GET method implementation using FastAPI
:return:
"""
return {"Hello": "World"}
view raw fast_api_sample.py hosted with ❤ by GitHub

Now let us run the application. The command to run the application is given below.

uvicorn fast_api_sample:app --reload

By default the app will run on port 8000. Open the URL http://127.0.0.1:8000 in your web browser.

Now lets check the API documentation of this application. Type the URL http://127.0.0.1:8000/docs . This will open up the Swagger UI

On expanding the GET method, you will be able to see the complete details of the API including options to try it out.

FastAPI generates ReDoc also. If you don’t like the Swagger UI, you can check the other API doc in the URL http://127.0.0.1:8000/redoc

I hope this example is helpful. I will be writing more about FastAPI in my upcoming posts. Feel free to comment if you have any questions.