【FastAPI】入门(一)

发布时间:2026/6/8 19:13:26

【FastAPI】入门(一) 【FastAPI】入门一1. 简介2.新建一个FastAPI项目3. Path函数4. 查询参数5. 请求体参数5.1 请求体参数 类型注解Field1. 简介官方教程https://fastapi.tiangolo.com/zh/tutorial/FastAPI 是一个用于构建 API 的现代、快速高性能的 Web 框架使用 Python 并基于标准的 Python 类型提示。关键特性快速极高性能可与 NodeJS 和 Go 并肩归功于 Starlette 和 Pydantic。最快的 Python 框架之一。高效编码功能开发速度提升约 200% 300%。更少 bug人为开发者错误减少约 40%。直观极佳的编辑器支持。处处皆可自动补全。更少的调试时间。易用为易用和易学而设计。更少的文档阅读时间。简短最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。健壮生产可用级代码。并带有自动生成的交互式文档。标准化基于并完全兼容API 的开放标准OpenAPI以前称为 Swagger和 JSON Schema。2.新建一个FastAPI项目fromfastapiimportFastAPI appFastAPI()app.get(/)asyncdefroot():return{message:Hello World}app.get(/hello/{name})asyncdefsay_hello(name:str):return{message:fHello{name}}app.get(/book/{id})asyncdefget_book(id:int):return{id:id,title:f这是第{id}本书}启动命令(FastAPI_first)➜ uvicorn main:app--reload其他启动命令实例uvicorn agentchat.main:app--port7860--host0.0.0.0接口文档http://127.0.0.1:8000/docs http://127.0.0.1:8000/redoc3. Path函数… 必填gt/ge 大于/大于等于lt/le 小于/ 小于等于descrtption 描述min_length/max_length 长度限制app.get(/book/{id})asyncdefget_book(id:intPath(...,gt0,lt101,descriptionBook id 取值范围1~100)):return{id:id,title:f这是第{id}本书}4. 查询参数5. 请求体参数fromfastapiimportFastAPI,PathfrompydanticimportBaseModel appFastAPI()classUser(BaseModel):username:strpassword:strapp.post(/register)asyncdefregister(user:User):return{username:user.username,password:user.password}5.1 请求体参数 类型注解Field

相关新闻