Last Updated on 2023-07-03 by Clay
Introduction
FastAPI is a modern, high-performance Python web framework. It is based on Python 3.7+ and utilizes Python type hints.
You might wonder, if you want to use Python to create a website, isn’t Flask or Django the most common choice? Why opt for FastAPI?
Below, I briefly document the differences between the FastAPI and Flask frameworks.
- Modernity and Standards
FastAPI is a relatively new framework, and it is specifically designed for RESTful APIs. It adopts modern Python features (such as type hints) and complies with the latest standards like OpenAPI and JSON Schema. In contrast, Flask is a more traditional, lightweight framework widely used for general web development.
2. Performance
FastAPI generally outperforms Flask in terms of performance. FastAPI is asynchronous, which enables it to handle a large number of requests more efficiently and usually with lower latency. On the other hand, Flask is synchronous and typically doesn’t perform as well as FastAPI under high load.
3. Type Checking and Data Validation
As mentioned above, FastAPI can use Python's type hints for automatic data validation and serialization. This not only eliminates a lot of boilerplate code but also provides automatically generated API documentation. In Flask, data validation and serialization usually have to be done manually.
4. Automatic Documentation Generation
FastAPI automatically generates interactive API documentation (through Swagger UI or ReDoc), making the development and testing process easier. Flask, on the other hand, requires third-party extensions to generate API documentation.
5. Learning Curve
For beginners, Flask might have a slightly gentler learning curve as it is designed to be simple and traditional. FastAPI, however, requires developers to be familiar with more modern features like asynchronous programming and type hints.
6. Community and Ecosystem
Flask has been around for a long time, so it has a large community and a plethora of plugins and extensions. FastAPI’s community is growing rapidly, but it is still smaller compared to Flask’s.
In conclusion, whether to choose FastAPI or Flask depends on the specific needs of the application you are designing.
For instance, if your main goal is to create RESTful APIs, then FastAPI might be the better choice as it is designed specifically for this.
But if you need a general-purpose web framework that can handle a variety of different types of applications, then Flask might be more suitable.
Next, let's briefly document the requirements, installation, and usage of FastAPI!
Requirements
Python 3.7+
Installation
pip install fastapi unicorn[standard]
You will need an ASGI server (Asynchronous Server Gateway Interface), so please also install uvicorn. The official documentation also mentions another tool, hypercorn. If needed, you might want to consider installing it as well.
Example
# main.pyfrom typing importUnionfrom fastapi import FastAPI
app = FastAPI()
@app.get("/")defread_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")defread_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
If you want to use asynchronous processing, then you need to write it in the following format:
# main.pyfrom typing importUnionfrom fastapi import FastAPI
app = FastAPI()
@app.get("/")asyncdefread_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")asyncdefread_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
And then you can do:
uvicorn main:app --reload
The --reload
parameter allows the interface to automatically reload every time the code is changed, without the need for manual restarting.
You can then experience the result by going to http://127.0.0.1:8000
, or test another route at http://127.0.0.1:8000/items/5?q=somequery
.
At this point, we have successfully created a test web page.
Some Help
We can get help on the current test features and routes from the URL below:
put
and post
Example
post
is an action to send requests for functionalities, while put
is an action to update existing data.
# coding: utf-8from typing importUnion, Dictfrom fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Database
hero_db = {}
# Hero data modelclassHero(BaseModel):
name: str
age: int
ability: str
hero_id: int# POST example: add a new [email protected]("/heroes/")asyncdefcreate_hero(hero: Hero):
hero_db[hero.hero_id] = hero.dict()
return {"Message": "Hero add", "data": hero}
@app.put("/heroes/{hero_id}")asyncdefupdate_hero(hero_id: int, hero: Hero):
if hero_id in hero_db:
hero_db[hero_id] = hero.dict()
return {"message": "Hero updated", "data": hero}
else:
return {"message": "Hero not found"}
Using post to add a new hero.
curl -X POST "http://127.0.0.1:8000/heroes/" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\":\"Batman\",\"age\":35,\"ability\":\"Martial Arts\",\"hero_id\":1}"
Using put to update the hero information.
curl -X PUT "http://127.0.0.1:8000/heroes/1" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\":\"Bruce Wayne\",\"age\":36,\"ability\":\"Detective\",\"hero_id\":1}"
At this point, we have completed some of the most basic operations of FastAPI.