当前位置: 首页 > news >正文

fastapi · FastAPI framework, high performance, easy to learn, fast to code, ready for production

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.

Kabir Khan -Microsoft(ref)

We adopted theFastAPIlibrary to spawn aRESTserver that can be queried to obtainpredictions. [for Ludwig]

Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala -Uber(ref)

Netflixis pleased to announce the open-source release of ourcrisis managementorchestration framework:Dispatch! [built withFastAPI]

Kevin Glisson, Marc Vilanova, Forest Monsen -Netflix(ref)

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.

Deon Pillsbury -Cisco(ref)

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:

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}.
  • BothpathstakeGEToperations(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: int

or 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.
  • Automatic interactive API documentation, including 2 alternative user interfaces:
    • Swagger UI.
    • ReDoc.

Coming back to the previous code example,FastAPIwill:

  • Validate that there is anitem_idin the path forGETandPUTrequests.
  • Validate that theitem_idis of typeintforGETandPUTrequests.
    • If it is not, the client will see a useful, clear error.
  • Check if there is an optional query parameter namedq(as inhttp://127.0.0.1:8000/items/foo?q=somequery) forGETrequests.
    • As theqparameter is declared with= None, it is optional.
    • Without theNoneit would be required (as is the body in the case withPUT).
  • ForPUTrequests to/items/{item_id}, read the body as JSON:
    • Check that it has a required attributenamethat should be astr.
    • Check that it has a required attributepricethat has to be afloat.
    • Check that it has an optional attributeis_offer, that should be abool, if present.
    • All this would also work for deeply nested JSON objects.
  • 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 constraintsasmaximum_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 andpytest
    • 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.dev

That’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 includesfastapi-cloud-cli, which allows you to deploy your FastAPI application to FastAPI Cloud.

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.

欢迎交流讨论,共同进步。

http://www.jsqmd.com/news/861356/

相关文章:

  • 鸿蒙PC的包管理工具 Homebrew 正式上线,Harmonybrew介绍及使用指南
  • 1987年5月15日中午11-13点出生性格、运势和命运
  • 从零开始学AI Agent:软件工程视角下的企业数字化转型实践指南(收藏版)
  • HBase 分布式集群部署实战:从解压到启动的完整指南
  • 健身 Agent:不止视频,更有 AI 人物实时跟练交互
  • 分享高三模拟卷资源盘点
  • 面试必看!大模型高频考点全覆盖(含LoRA、DPO、MoE、ZeRO、KV Cache等核心问题)
  • ZFX山海证券:“消费转向考验零售韧性”
  • 离散几何拓扑数论(终稿·全定义完整版一)
  • 网卡服务与配置
  • 2026年WMS软件怎么选?10款主流WMS软件功能对比与避坑指南
  • 第九届蓝桥杯国赛b组--备战国赛版h
  • 2026年京东云OpenClaw/Hermes Agent配置Token Plan集成一篇搞定
  • 8G 内存无独显也能跑!零基础本地部署轻量化私人 AI(完整版实操教程)
  • 【无标题】认识Python的数据可视化
  • ascend-transformer-boost:Transformer加速库架构原理剖析
  • 指控系统中态势感知与OODA双螺旋智能系统
  • 1987年6月27日下午13-15点出生性格、运势和命运
  • 沥青生产导向的常减压过程模拟及排产计划优化【附仿真】
  • 人工智能将如何创造就业:从岗位替代到生态重构的深度解析
  • 通过 API 实时监听企业微信外部群变更事件并同步本地数据库
  • android使用websocket
  • 3步实现百度网盘高速下载:Python解析工具实战指南
  • 2026年5月降AI软件红黑榜出炉:论文AI率90%降至3.8%,精准去除ai痕迹!
  • 千问 LeetCode 2538. 最大价值和与最小价值和的差值 Go实现
  • 如何构建一个健康的学术生态
  • Apache 2.4 版本如何启用 TLS 1.3 并配置 SSL 证书路径
  • 别再混用 Skill 和 Workflow:它俩不是一层东西
  • 耿同学正在推动中国科技进步
  • 【多通道滤波】基于最小均方(McFxLMS)算法用于自适应多通道有源噪声控制(MCANC)应用研究(Matlab代码实现)