Home

Awesome

<p align="center"> <a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a> </p> <p align="center"> <em>FastAPI 框架,高性能,易学,快速编码,随时可供生产</em> </p> <p align="center"> <a href="https://travis-ci.com/tiangolo/fastapi" target="_blank"> <img src="https://travis-ci.com/tiangolo/fastapi.svg?branch=master" alt="Build Status"> </a> <a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank"> <img src="https://codecov.io/gh/tiangolo/fastapi/branch/master/graph/badge.svg" alt="Coverage"> </a> <a href="https://pypi.org/project/fastapi" target="_blank"> <img src="https://badge.fury.io/py/fastapi.svg" alt="Package version"> </a> <a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank"> <img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi"> </a> </p>

文档<a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>

源码<a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>


FastAPI 是一个现代、快速(高性能)的 Web 框架,基于标准 Python 类型提示,使用 Python 3.6+ 构建 API。

主要功能包括:

<small>* 根据内部开发团队的测试进行估算,以构建生产应用程序。</small>

观点

"[...] I'm using FastAPI a ton these days. [...] I'm actually planning to use it for all of my team's ML services at Microsoft. Some of them are getting integrated into the core Windows product and some Office products."

<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div> ---

"I’m over the moon excited about FastAPI. It’s so fun!"

<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> podcast host</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div> ---

"Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted Hug to be - it's really inspiring to see someone build that."

<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="http://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div> ---

"If you're looking to learn one modern framework for building REST APIs, check out FastAPI [...] It's fast, easy to use and easy to learn [...]"

"We've switched over to FastAPI for our APIs [...] I think you'll like it [...]"

<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> founders - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div> ---

"We adopted the FastAPI library to spawn a REST server that can be queried to obtain predictions. [for Ludwig]"

<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div> ---

Typer,CLI中的FastAPI

<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>

如果要构建用于终端而不是Web API的CLI(Command Line Interface)应用,请查看<a href="https://typer.tiangolo.com/" class="external-link" target="_blank">Typer</a>

Typer是FastAPI的小兄弟。它打算成为CLI中的FastAPI。⌨️ 🚀

依赖

Python 3.6+

FastAPI站在巨人的肩膀上:

安装

$ pip install fastapi

---> 100%

你还需要一个ASGI服务器来进行生产,例如<a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 或者 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>

$ pip install uvicorn

---> 100%

示例

创建

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):
    return {"item_id": item_id, "q": q}
<details markdown="1"> <summary>或者使用<code>async def</code>...</summary> <p>如果你的代码使用 <code>async</code> / <code>await</code>,请使用 <code>async def</code>:</p> <div class="highlight highlight-source-python"><pre><span class="pl-k">from</span> fastapi <span class="pl-k">import</span> FastAPI

app <span class="pl-k">=</span> FastAPI()

<span class="pl-en">@app.get</span>(<span class="pl-s"><span class="pl-pds">"</span>/<span class="pl-pds">"</span></span>) <span class="pl-k">async</span> <span class="pl-k">def</span> <span class="pl-en">read_root</span>(): <span class="pl-k">return</span> {<span class="pl-s"><span class="pl-pds">"</span>Hello<span class="pl-pds">"</span></span>: <span class="pl-s"><span class="pl-pds">"</span>World<span class="pl-pds">"</span></span>}

<span class="pl-en">@app.get</span>(<span class="pl-s"><span class="pl-pds">"</span>/items/<span class="pl-c1">{item_id}</span><span class="pl-pds">"</span></span>) <span class="pl-k">async</span> <span class="pl-k">def</span> <span class="pl-en">read_item</span>(<span class="pl-smi">item_id</span>: <span class="pl-c1">int</span>, <span class="pl-smi">q</span>: <span class="pl-c1">str</span> <span class="pl-k">=</span> <span class="pl-c1">None</span>): <span class="pl-k">return</span> {<span class="pl-s"><span class="pl-pds">"</span>item_id<span class="pl-pds">"</span></span>: item_id, <span class="pl-s"><span class="pl-pds">"</span>q<span class="pl-pds">"</span></span>: q}</pre></div>

<p><strong>注意</strong>:</p> <p>如果你不知道,请在文档中的 <em>"急吗?"</em> 查看有关 <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" rel="nofollow"><code>async</code> 和 <code>await</code></a>的部分。</p> </details>

运行

使用以下命令运行服务:

$ uvicorn main:app --reload

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [28720]
INFO:     Started server process [28722]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
<details> <summary>关于 <code>uvicorn main:app --reload</code>命令...</summary> <p><code>uvicorn main:app</code> 命令指:</p> <ul> <li><code>main</code>:<code>main.py</code>文件(Python“模块”)。</li> <li><code>app</code>:在<code>main.py</code>内部创建的对象,其中的行是<code>app = FastAPI()</code>。</li> <li><code>--reload</code>:使服务在代码更改后重新启动。 仅在开发时这样做。</li> </ul> </details>

检查

在浏览器中打开 <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>

你会看到 JSON 响应像是:

{"item_id": 5, "q": "somequery"}

你已经创建了一个API:

交互式API文档

现在前往 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>

你将看到自动交互式API文档(由<a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>提供):

Swagger UI

备用的API文档

现在,前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>

你将看到备用的自动文档(由<a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>提供):

ReDoc

示例升级

现在修改文件main.py以接收来自PUT请求的主体。

使用标准的Python类型声明主体,感谢Pydantic。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = 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}

服务应该会自动重新加载(因为你在上面的uvicorn命令中添加了--reload)。

交互式API文档升级

现在前往 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>

Swagger UI

Swagger UI interaction

Swagger UI interaction

备用API文档升级

现在,前往 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>

ReDoc

概括

总而言之,你一次性将参数的类型,主体等声明为函数参数。

你可以使用标准的现代Python类型来做到这一点。

你不必学习新的语法,特定库的方法或类等。

只是标准的Python 3.6 +

例如,对于一个int

item_id: int

或更复杂的Item模型:

item: Item

...通过单个声明,你将得到:


回到前面的代码示例,FastAPI将:


我们只是从头开始,但你已经了解了所有工作原理。

尝试使用以下更改:

    return {"item_name": item.name, "item_id": item_id}

...从:

        ... "item_name": item.name ...

...到:

        ... "item_price": item.price ...

...并查看编辑器如何自动补全属性并了解其类型:

editor support

有关包含更多功能的更完整示例,请参阅<a href="https://fastapi.tiangolo.com/tutorial/">教程-用户指南</a>

剧透警报:教程-用户指南包括:

性能

独立的TechEmpower基准测试显示FastAPI应用程序在Uvicorn下运行为<a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">最快的Python框架之一</a>,仅在Starlette和Uvicorn(由FastAPI内部使用)之下。

要了解更多信息,请参阅<a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">基准测试</a>

可选依赖项

使用Pydantic:

使用Starlette:

使用FastAPI/Starlette:

你可以使用pip install fastapi[all]安装所有这些。

许可证

该项目根据MIT许可条款获得许可。