I. Introduction
Recently I'm doing web development, the web with front and back ends separated. The front-end framework uses Vue, the front-end component library is Element-UI, and the back-end is hovering in Django-Rest-Framework, Flask, and FastApi. Tested one by one. Finally, FastApi was chosen.
The reasons are as follows:
- Django-Rest-Framework: It feels cumbersome, and the official documentation is not friendly enough for novices, and it is more difficult for me, a layman in web development.
- Flask: It's relatively lightweight, but it's not very suitable for api development, and it needs specific functions for conversion.
- FastApi: It has its own api documentation (the interface is very beautiful, and there is no need to write additional pages for testing during development), and it is very friendly to the json format api.
The following picture shows the built-in test interface:
2. Case
Hello World
The following is a case of Hello world. Create a new helloworld.py
script.
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {
"message": "Hello World"}
uvicorn.run(app=app)
In the above script, uvicorn
it is a ASGI
server. The default port 8000
, the default host
is localhost
. It may be performed by the following methods port
and host
modifications.
Use app.get('/')
registered route, when the address is accessed, the dictionary will return the corresponding ( JSON
string)
uvicorn.run(app, host="127.0.0.1", port=8000)
Open 127.0.0.1:8000/docs to test. Test results using docs
Bringing such a document has a great advantage-it reduces the time to write a test interface. FastApi can also directly use the JSON
format return (also supports there are better ways, such as on the case below)
In this case, the advantages of docs are not reflected. Because you don't need any input, you can get the output.
input Output
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
class UserIn(BaseModel):
username: str
password: str
email: EmailStr
full_name: str = None
class UserOut(BaseModel):
username: str
email: EmailStr
full_name: str = None
@app.post("/user/", response_model=UserOut)
async def create_user(*, user: UserIn):
return user
# pip install pydantic[email]
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
In the function, define parameters for the user: UserIn
show need to enter the data in line with UserIn
the model. Configured response_model
to UserOut
, indicating that the output data are consistent with UserOut
the model. FastApi will automatically filter
enter
Output
The built-in document can display all the schemas (Schemas), which will correspond to the classes in the code (you can use the dictionary to initialize quickly).
Other advantages
- Other templates can be introduced
- Official tutorial very friendly to novices