fastapi · FastAPI framework, high performance, easy to learn, fast to code, ready for production
本文整理自 GitHub,经重新整理编辑。
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Documentation: https://fastapi.tiangolo.com
Source Code: https://github.com/fastapi/fastapi
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.
The key features are:
- Fast: Very high performance, on par withNodeJSandGo(thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
- Fast to code: Increase the speed to develop features by about 200% to 300%. *
- Fewer bugs: Reduce about 40% of human (developer) induced errors. *
- Intuitive: Great editor support.Completioneverywhere. Less time debugging.
- Easy: Designed to be easy to use and learn. Less time reading docs.
- Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
- Robust: Get production-ready code. With automatic interactive documentation.
- Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
* estimation based on tests conducted by an internal development team, building production applications.
Sponsors
Keystone Sponsor
Gold Sponsors
Silver Sponsors
Other sponsors
Opinions
“[…] I’m usingFastAPIa ton these days. […] I’m actually planning to use it for all of my team’sML services at Microsoft. Some of them are getting integrated into the coreWindowsproduct and someOfficeproducts.”
“We adopted theFastAPIlibrary to spawn aRESTserver that can be queried to obtainpredictions. [for Ludwig]”
“Netflixis pleased to announce the open-source release of ourcrisis managementorchestration framework:Dispatch! [built withFastAPI]”
“If anyone is looking to build a production Python API, I would highly recommendFastAPI. It isbeautifully designed,simple to useandhighly scalable, it has become akey componentin our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer.”
FastAPI Conf
FastAPI Conf '26is happening onOctober 28, 2026inAmsterdam, NL. All about FastAPI, right from the source. 🎤
FastAPI mini documentary
There’s a FastAPI mini documentary released at the end of 2025, you can watch it online:
Typer, the FastAPI of CLIs
If you are building a CLIapp to be used in the terminal instead of a web API, check outTyper.
Typeris FastAPI’s little sibling. And it’s intended to be theFastAPI of CLIs. ⌨️ 🚀
Requirements
FastAPI stands on the shoulders of giants:
- Starlette for the web parts.
- Pydantic for the data parts.
Installation
Create and activate a virtual environment and then install FastAPI:
$ pip install "fastapi[standard]" ---> 100%Note: Make sure you put"fastapi[standard]"in quotes to ensure it works in all terminals.
Example
Create it
Create a filemain.pywith:
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q}Or useasync def...If your code usesasync/await, useasync def:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q}Note:
If you don’t know, check the“In a hurry?”section aboutasyncandawaitin the docs.
Run it
Run the server with:
$ fastapi dev ╭────────── FastAPI CLI - Development mode ───────────╮ │ │ │ Serving at: http://127.0.0.1:8000 │ │ │ │ API docs: http://127.0.0.1:8000/docs │ │ │ │ Running in development mode, for production use: │ │ │ │ fastapi run │ │ │ ╰─────────────────────────────────────────────────────╯ INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [2248755] using WatchFiles INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete.About the commandfastapi dev...The commandfastapi devreads yourmain.pyfile automatically, detects theFastAPIapp in it, and starts a server using Uvicorn.
By default,fastapi devwill start with auto-reload enabled for local development.
You can read more about it in the FastAPI CLI docs.
Check it
Open your browser at http://127.0.0.1:8000/items/5?q=somequery.
You will see the JSON response as:
{"item_id": 5, "q": "somequery"}You already created an API that:
- Receives HTTP requests in thepaths
/and/items/{item_id}. - Bothpathstake
GEToperations(also known as HTTPmethods). - Thepath
/items/{item_id}has apath parameteritem_idthat should be anint. - Thepath
/items/{item_id}has an optionalstrquery parameterq.
Interactive API docs
Now go to http://127.0.0.1:8000/docs.
You will see the automatic interactive API documentation (provided by Swagger UI):
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a9hmlAeb-1779376834056)(https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)]
Alternative API docs
And now, go to http://127.0.0.1:8000/redoc.
You will see the alternative automatic documentation (provided by ReDoc):
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tVuDH7YS-1779376834057)(https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)]
Example upgrade
Now modify the filemain.pyto receive a body from aPUTrequest.
Declare the body using standard Python types, thanks to Pydantic.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool | None = None @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q} @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id}Thefastapi devserver should reload automatically.
Interactive API docs upgrade
Now go to http://127.0.0.1:8000/docs.
- The interactive API documentation will be automatically updated, including the new body:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qmPaz3BR-1779376834057)(https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)]
- Click on the button “Try it out”, it allows you to fill the parameters and directly interact with the API:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-giRciojw-1779376834057)(https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png)]
- Then click on the “Execute” button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3N7ucuha-1779376834057)(https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png)]
Alternative API docs upgrade
And now, go to http://127.0.0.1:8000/redoc.
- The alternative documentation will also reflect the new query parameter and body:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VlAOyXOE-1779376834058)(https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)]
Recap
In summary, you declareoncethe types of parameters, body, etc. as function parameters.
You do that with standard modern Python types.
You don’t have to learn a new syntax, the methods or classes of a specific library, etc.
Just standardPython.
For example, for anint:
item_id: intor for a more complexItemmodel:
item: Item…and with that single declaration you get:
- Editor support, including:
- Completion.
- Type checks.
- Validation of data:
- Automatic and clear errors when the data is invalid.
- Validation even for deeply nested JSON objects.
- Conversionof input data: coming from the network to Python data and types. Reading from:
- JSON.
- Path parameters.
- Query parameters.
- Cookies.
- Headers.
- Forms.
- Files.
- Conversionof output data: converting from Python data and types to network data (as JSON):
- Convert Python types (
str,int,float,bool,list, etc). datetimeobjects.UUIDobjects.- Database models.
- …and many more.
- Convert Python types (
- Automatic interactive API documentation, including 2 alternative user interfaces:
- Swagger UI.
- ReDoc.
Coming back to the previous code example,FastAPIwill:
- Validate that there is an
item_idin the path forGETandPUTrequests. - Validate that the
item_idis of typeintforGETandPUTrequests.- If it is not, the client will see a useful, clear error.
- Check if there is an optional query parameter named
q(as inhttp://127.0.0.1:8000/items/foo?q=somequery) forGETrequests.- As the
qparameter is declared with= None, it is optional. - Without the
Noneit would be required (as is the body in the case withPUT).
- As the
- For
PUTrequests to/items/{item_id}, read the body as JSON:- Check that it has a required attribute
namethat should be astr. - Check that it has a required attribute
pricethat has to be afloat. - Check that it has an optional attribute
is_offer, that should be abool, if present. - All this would also work for deeply nested JSON objects.
- Check that it has a required attribute
- Convert from and to JSON automatically.
- Document everything with OpenAPI, that can be used by:
- Interactive documentation systems.
- Automatic client code generation systems, for many languages.
- Provide 2 interactive documentation web interfaces directly.
We just scratched the surface, but you already get the idea of how it all works.
Try changing the line with:
return {"item_name": item.name, "item_id": item_id}…from:
... "item_name": item.name ...…to:
... "item_price": item.price ...…and see how your editor will auto-complete the attributes and know their types:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LKopHHVz-1779376834058)(https://fastapi.tiangolo.com/img/vscode-completion.png)]
For a more complete example including more features, see the Tutorial - User Guide.
Spoiler alert: the tutorial - user guide includes:
- Declaration ofparametersfrom other different places as:headers,cookies,form fieldsandfiles.
- How to setvalidation constraintsas
maximum_lengthorregex. - A very powerful and easy to useDependency Injectionsystem.
- Security and authentication, including support forOAuth2withJWT tokensandHTTP Basicauth.
- More advanced (but equally easy) techniques for declaringdeeply nested JSON models(thanks to Pydantic).
- GraphQLintegration with Strawberry and other libraries.
- Many extra features (thanks to Starlette) as:
- WebSockets
- extremely easy tests based on HTTPX and
pytest - CORS
- Cookie Sessions
- …and more.
Deploy your app (optional)
You can optionally deploy your FastAPI app to FastAPI Cloud, go and join the waiting list if you haven’t. 🚀
If you already have aFastAPI Cloudaccount (we invited you from the waiting list 😉), you can deploy your application with one command.
$ fastapi deploy Deploying to FastAPI Cloud... ✅ Deployment successful! 🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.devThat’s it! Now you can access your app at that URL. ✨
About FastAPI Cloud
FastAPI Cloudis built by the same author and team behindFastAPI.
It streamlines the process ofbuilding,deploying, andaccessingan API with minimal effort.
It brings the samedeveloper experienceof building apps with FastAPI todeployingthem to the cloud. 🎉
FastAPI Cloud is the primary sponsor and funding provider for theFastAPI and friendsopen source projects. ✨
Deploy to other cloud providers
FastAPI is open source and based on standards. You can deploy FastAPI apps to any cloud provider you choose.
Follow your cloud provider’s guides to deploy FastAPI apps with them. 🤓
Performance
Independent TechEmpower benchmarks showFastAPIapplications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
To understand more about it, see the section Benchmarks.
Dependencies
FastAPI depends on Pydantic and Starlette.
standardDependencies
When you install FastAPI withpip install "fastapi[standard]"it comes with thestandardgroup of optional dependencies:
Used by Pydantic:
email-validator- for email validation.
Used by Starlette:
httpx- Required if you want to use theTestClient.jinja2- Required if you want to use the default template configuration.python-multipart- Required if you want to support form“parsing”, withrequest.form().
Used by FastAPI:
uvicorn- for the server that loads and serves your application. This includesuvicorn[standard], which includes some dependencies (e.g.uvloop) needed for high performance serving.fastapi-cli[standard]- to provide thefastapicommand.- This includes
fastapi-cloud-cli, which allows you to deploy your FastAPI application to FastAPI Cloud.
- This includes
WithoutstandardDependencies
If you don’t want to include thestandardoptional dependencies, you can install withpip install fastapiinstead ofpip install "fastapi[standard]".
Withoutfastapi-cloud-cli
If you want to install FastAPI with the standard dependencies but without thefastapi-cloud-cli, you can install withpip install "fastapi[standard-no-fastapi-cloud-cli]".
Additional Optional Dependencies
There are some additional dependencies you might want to install.
Additional optional Pydantic dependencies:
pydantic-settings- for settings management.pydantic-extra-types- for extra types to be used with Pydantic.
Additional optional FastAPI dependencies:
orjson- Required if you want to useORJSONResponse.ujson- Required if you want to useUJSONResponse.
License
This project is licensed under the terms of the MIT license.
欢迎交流讨论,共同进步。