This article records in detail the local installation and operation of FastAPI, which is very simple, and mainly records and verifies some features.
Install FastAPI
The installation is very simple, you only need to install two packages:
- FastAPI
copypip install fastapi
- uvicorn - Server for loading and serving applications.
copypip install uvicorn
create project
- FastAPI project can be created directly in pycharm 2022 version, I don’t know if it is possible in other versions, just create it directly;
If not, don't panic, just create an empty project. Just paste the following code in the main.py file: from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"}
- run project The first is the project created by pycharm, just run it directly
Another is to create it directly, just enter and run the command uvicorn main:app --reload in the terminal
- Check the running effect: http://127.0.0.1:8000/
Output the JSON data, and the build is successful.
Interactive API Documentation
Open http://127.0.0.1:8000/docs to see the automatically generated interactive API documentation (by Swagger UI supply):
Optional API Documentation
Go to http://127.0.0.1:8000/redoc to see optional auto-generated documentation (by ReDoc supply):
Source code analysis
copyfrom fastapi import FastAPI
Import the fastapi package
copyapp = FastAPI()
Create a FastAPI instance The variable app here will be an "instance" of the FastAPI class. This instance will be the main interaction object for creating all your API s. This app is also referenced by uvicorn in the command: uvicorn main:app --reload
copy@app.get("/")
Tell FastAPI that the function below it is responsible for handling the following access requests:
- path is /
- Use the get request method
The @something syntax is called a "decorator" in Python, and a decorator takes a function beneath it and uses it to do some work. Common path manipulation decorators:
copy@app.post("/") @app.put("/") @app.delete("/") @app.get("/") @app.options("/") @app.head("/") @app.patch("/") @app.trace("/") async def root(): return {"message": "Hello World"}
copyasync def root(): return {"message": "Hello World"}
async defines an asynchronous function that will be called every time/request and returns {"message": "Hello World"}
configuration item
Mainly some basic configuration items, such as access addresses of two API addresses, document title and introduction, etc. These can directly look at the source code:
copyclass FastAPI(Starlette): def __init__( self, *, debug: bool = False, routes: Optional[List[BaseRoute]] = None, title: str = "FastAPI", description: str = "", version: str = "0.1.0", openapi_url: Optional[str] = "/openapi.json", openapi_tags: Optional[List[Dict[str, Any]]] = None, servers: Optional[List[Dict[str, Union[str, Any]]]] = None, dependencies: Optional[Sequence[Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), docs_url: Optional[str] = "/docs", redoc_url: Optional[str] = "/redoc", swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect", swagger_ui_init_oauth: Optional[Dict[str, Any]] = None, middleware: Optional[Sequence[Middleware]] = None, exception_handlers: Optional[ Dict[ Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]], ] ] = None, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, terms_of_service: Optional[str] = None, contact: Optional[Dict[str, Union[str, Any]]] = None, license_info: Optional[Dict[str, Union[str, Any]]] = None, openapi_prefix: str = "", root_path: str = "", root_path_in_servers: bool = True, responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, swagger_ui_parameters: Optional[Dict[str, Any]] = None, generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( generate_unique_id ), **extra: Any, )
The parameters are relatively clear, such as whether to enable debug mode, title, introduction, version, etc. The simple configuration is as follows:
copyapp = FastAPI( title='FastAPI Study', description='FastAPI tutorial', version='1.0.0', docs_url='/docs', redoc_url='/redocs', )
Renderings: