Skip to main content

Introduction

fastapi-cover

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

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

Features

The key features are:

  • Fast: Very high performance, on par with NodeJS and Go (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. Completion everywhere. 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.
  • 精简编码 代码重复率低
  • 自带 APl 交互文档 开发成果随时交付
  • API 开发标准化,比如标准的 error message
note
  • 2019 年创建
  • 还未发布 1.0 版本
  • 可以用在产线
  • 作者是德国人
  • 基于 Python 3.7+
  • 将各个优秀的框架组合起来+ python type hints
  • 内置了 Swagger 文档

Install

一键安装:

pip install "fastapi[all]"

以上将同时安装 uvicorn,如果没有写 [all] 则需要两个都安装:

pip install fastapi
pip install uvicorn

验证安装结果:

$ python
>>>import fastapi
>>>fastapi.__version__
uvicorn --version

Hello World

The simplest FastAPI file could look like this:

main.py
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
async def root(): # you can also remove async keyword
return {"message": "Hello World"}

Copy that to a file main.py.

Run the live server:

$ 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.
tip

The command uvicorn main:app refers to:

  • main: the file main.py (the Python "module").
  • app: the object created inside of main.py with the line app = FastAPI().
  • --reload: make the server restart after code changes. Only use for development.

The default port is "8000", and now you can open http://127.0.0.1:8000/docs to see the automatic interactive API documentation (provided by Swagger UI):

TGmeym

You can also add __name__ on the bottom of main.py:

main.py
if __name__ == "__main__":
uvicorn.run("main:app") # or uvicorn.run(app="main:app")

And then run python main.py to start server directly.

参数作用
app运行的 py 文件:FastAPI 实例对象
host访问 url,默认 127.0.0.1
port访问端口,默认 8080
reload热更新,有内容修改自动重启服务器
debugreload
reload_dirs设置需要 reload 的目录,List[str] 类型
log_level设置日志级别,默认 info

References

  1. FastAPI official document
  2. uvicorn.run() 常用参数 by ajin945