FastAPI
Like any web framework, FastAPI helps you to build web applications.
Some advantages claimed by the website include:
* Performance
: As fast as Node and Golang in some cases, unusual for Python frameworks.
* Faster development
: No sharp edges or oddities.
* Better code quality
: Type hinting and models help reduce bugs.
* Autogenerated documentation and test pages
: Much easier than hand editing OpenAPI descriptions.
FastAPI uses: * Python type hints * Starlette for the web machinery, including async support * Pydantic for data definitions and validation * Special integration to leverage and extend the others
Web Server
FastAPI itself does not include a web server, but recommends Uvicorn
.
HTTP Requests
The way that FastAPI provides data from various parts of the HTTP requests is one of its best features, and an improvement on how most Python web frameworks do it. All the arguments that you need can be declared and provided directly inside the path function, using the definitions above (Path
, Query
, etc.), and by functions that you write. This uses a technique called dependency injection
.
FastAPI converts HTTP header keys to lowercase
, and dash (-
) to underscore (_
).
By default, FastAPI converts whatever you return from your endpoint function to JSON
.
By default, FastAPI returns a 200
status code; exceptions raise 40x
codes.
Response Model
It’s possible to have different classes with many of the same fields, except one is specialized for user input, one for output, and one for internal use:
- Remove some sensitive information from output (like deidentifying personal medical data, if you’ve encountered HIPPA requirements).
- Add fields to user input (like a creation date and time).
You can return other data types than the default JSON from a FastAPI path function in different ways. One method is to use the response_model
argument in the path decorator to goose FastAPI to return something else. FastAPI will drop any fields that were in the object that you returned but are not in the object specified by response_model.