fastapi是高性能的web框架。他的主要特点是:

  • 快速编码
  • 减少人为bug
  • 直观
  • 简易
  • 具有交互式文档
  • 基于API的开放标准(并与之完全兼容):OpenAPI(以前称为Swagger)和JSON Schema。

技术背景:python3.6+、Starlette、Pydantic

官方文档地址:https://fastapi.tiangolo.com/

安装

pip install fastapi
pip install uvicorn

quick start

# main.py

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}

或者

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):
return {"item_id": item_id, "q": q}

运行

uvicorn main:app --reload

看到如下提示,证明运行成功

main: 表示app所在文件名
app:FastAPI实例
reload:debug模式,可以自动重启

试着请求http://127.0.0.1:8000/items/5?q=somequery,会看到如下返回

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

交互文档

试着打开http://127.0.0.1:8000/docs

API文档

试着打开http://127.0.0.1:8000/redoc

update

通过上面的例子,我们已经用fastapi完成了第一个web服务,现在我们再添加一个接口


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}

此时会发现,服务自动重启了,这是因为我们在启动命令后添加了--reload。再次查看文档,发现同样发生了改变。

到此,你已经可以快速的用fastapi搭建起服务了~

最新文章

  1. Java Web之Filter
  2. XAML数据绑定(Data Binding)
  3. UVa 2197 & 拆点分环费用流
  4. C#中截取字符串的几种方法
  5. MySQL分区表
  6. ZooKeeper学习第三期---Zookeeper命令操作
  7. (转)C#精确时间计时器
  8. (ArcGIS API For Silverlight )QueryTask 跨层查询,和监控完整的查询!
  9. 使用shell脚本自定义实现选择登录ssh
  10. Eclipse:The selection cannot be launched,and there are no recent launches
  11. solr安装血泪史
  12. makefile 和shell文件相互调用
  13. 重庆3Shape Dental System技术支持
  14. conda添加多个版本的python
  15. python--第十一天总结(paramiko 及数据库操作)
  16. MySQL DeadLock故障排查过程
  17. SEO笔记:Anatomy of a URL
  18. C++中函数模版与类模版
  19. gi的安装和使用
  20. 【AC自动机】HDU中模板题

热门文章

  1. NIO.2中Path、 Paths、Files类的使用
  2. 匿名对象作为方法的参数和返回值与Random概念和基本使用
  3. Ant Design Vue 走马灯实现单页多张图片轮播
  4. Tomcat深入浅出——最终章(六)
  5. Vue中关于this指向的问题
  6. Cayley 公式的另一种证明
  7. HTML表单学习
  8. 技术分享 | 测试git上2500星的闪回小工具
  9. JavaScript 里三个点 ...,可不是省略号啊···
  10. Word 常识备忘录