FastAPI基础入门

第一个FastAPI

python 复制代码
from fastapi import FastAPI

# 创建API实例
app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello FastAPI on PyCharm Community"}

路由

python 复制代码
import uvicorn
from fastapi import FastAPI

# 创建API实例
app = FastAPI()

@app.get("/")
async def get_hello():
    return "hello world"

参数简介和路径参数

python 复制代码
import uvicorn
from fastapi import FastAPI

# 创建API实例
app = FastAPI()

# 路径参数
@app.get("/book/{id}")
async def get_book(id: int):
    return {"id":id,"title":f"这是第{id}本书"}

路径参数_Path类型注解

python 复制代码
import uvicorn
from fastapi import FastAPI,Path

# 创建API实例
app = FastAPI()

# 路径参数_path类型注解
@app.get("/school/{id}")
async def get_school(id: int = Path(...,gt=0,lt=100,description="查询学校的接口")):
    return {"id":id,"title":f"这是第{id}个学校"}

# 需求,查找书籍的作者,路径参数 name,长度范围 2 - 10
@app.get("/user/{id}")
async def get_name(name: str = Path(...,min_length=2,max_length=10)):
    return {"msg": f"这是 {name}的信息"}

查询参数和Query类型注解

python 复制代码
import uvicorn
from fastapi import FastAPI,Query

# 创建API实例
app = FastAPI()

# 查询参数和Query类型注解
# http://www.baidu.com?skip=&limit=&
@app.get("/news/news_list")
async def get_news_list(skip: int = Query(0,description="跳过的记录数",lt=100),
                        limit: int = Query(10,description="返回的记录数")
                        ):
    return {"skip":skip,"limit":limit}

请求体参数

python 复制代码
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel

# 创建API实例
app = FastAPI()

# 请求体参数
# 注册:用户名和密码 -> str
class User(BaseModel):
    username: str
    password: str

@app.post("/register")
async def register(user: User):
    return user

请求体参数-Field类型注解

python 复制代码
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel,Field

# 创建API实例
app = FastAPI()

# 请求体参数Field类型注解
# 注册:用户名和密码 -> str
class User(BaseModel):
    username: str = Field("张三",min_length=2,max_length=10,description="用户名,长度要求2-10个字")
    password: str = Field(min_length=3,max_length=20)

@app.post("/register")
async def register(user: User):
    return user

响应参数-JSON格式

python 复制代码
import uvicorn
from fastapi import FastAPI

# 创建API实例
app = FastAPI()

# 响应格式-JSON
@app.get("/response_json")
async def get_response_json():
    return {"message":"hello world"}

响应参数-HTML格式

python 复制代码
import uvicorn
from fastapi import FastAPI
from starlette.responses import HTMLResponse, FileResponse

# 创建API实例
app = FastAPI()

# 响应格式-HTML
@app.get("/response_html",response_class=HTMLResponse)
async def get_html():
    return "<h1>这是一级标题</h1>"

响应参数-文件格式

python 复制代码
# 响应格式-文件类型
import uvicorn
from fastapi import FastAPI
from starlette.responses import HTMLResponse, FileResponse

# 创建API实例
app = FastAPI()
# 返回一张图片内容
@app.get("/response_file")
async def get_file():
    path = "./files/1.jpeg"
    return FileResponse(path)

自定义响应格式

python 复制代码
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel,Field
from starlette.responses import HTMLResponse, FileResponse

# 创建API实例
app = FastAPI()

# 需求:新闻接口 -> 响应数据格式 id、title、content
class News(BaseModel):
    id: int
    title: str
    content: str
@app.post("/news/{id}",response_model=News)
async def get_news(id: int):
   return {
       "id":id,
       "title":f"这是第{id}本书",
       "content":"这是一本好书"
   }

异常响应处理

python 复制代码
import uvicorn
from fastapi import FastAPI,HTTPException

# 创建API实例
app = FastAPI()

# 异常响应处理
# 需求:按id新闻查询 -> 1 - 6
@app.get("/get/exc/news/{id}")
async def get_exc_news(id: int):
    id_list = [1,2,3,4,5,6]
    if id not in id_list:
       raise HTTPException(status_code=404,detail="您查找的新闻不存在")
    return {"id":id}
相关推荐
Bruce_Liuxiaowei3 小时前
从零到可运行:基于 Vue3 + FastAPI + DeepSeek-V3 的 AI 英语单词学习系统全栈实战
人工智能·python·学习·fastapi·全栈·智能体
卷无止境11 小时前
FastAPI的测试事件在测什么?
后端·python·fastapi
卷无止境11 小时前
FastAPI CLI 你需要认识这把命令行利器
后端·python·fastapi
卷无止境1 天前
FastAPI 的 WebSocket 装了些什么
后端·python·fastapi
卷无止境2 天前
FastAPI 权限管理实战:从 ACL 到 RBAC 的那些门道
后端·python·fastapi
云和数据.ChenGuang3 天前
fastapi的参数剖析
人工智能·深度学习·机器学习·语言模型·状态模式·fastapi
Python私教4 天前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教4 天前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
weixin_471383034 天前
08 Chroma 持久化 + FastAPI 封装
fastapi·chroma
京东云开发者4 天前
【全栈实践】第一个 AI Agent 项目:从零搭建 AI 音频创作助手(进阶篇)
typescript·fastapi·vuex