FastApi入门

发布时间:2026/7/4 3:10:30

FastApi入门 第一个fastapi程序from fastapi import FastAPI app FastAPI() app.get(/) async def root(): return {message: Hello World} app.get(/hello/{name}) async def say_hello(name: str): return {message: fHello {name}}路由fastapi的路由定义基于python的装饰器模式app.get(/hello/{name}) async def say_hello(name: str): return {message: fHello {name}}同一个接口参数不同可以返回不同的数据参数分类路径参数--类型注解Pathfastapi允许为参数声明额外信息和校验1.导入Path函数path函数常用的参数app.get(/book/{id}) async def get_book(id: int Path(..., gt0, le100, descriptionThe id of the book to get)): return {id: id,title: The Great Gatsby, author: F. Scott Fitzgerald}查询参数--url之后的参数app.get(/book/news_list) async def get_book_list(id: int Query(..., gt0, le100, descriptionThe id of the book to get)): return { id: id, title: The Great Gatsby, author: F. Scott Fitzgerald }请求体参数HTTP的一个请求包含三部分1.请求行包含方法url,协议版本2.请求头元数据信息(Content-Type,Authorization等)3.请求体实际要发送的数据内容具体使用步骤1.定义类型from pydantic import BaseModel #BaseModel的作用是接受HTTP请求中的json格式的参数并将其转换成User类型 class User(BaseModel): username: str password: str2.类型注解app.post(/register) async def register(user: User): return user类型注解Field导入pydantic的Field函数from pydantic import BaseModel,Field class User(BaseModel): username: str Field(default张三,min_length2,max_length10,description用户名要求2-10个字符) password: str Field(min_length3,max_length20)Field常见的参数请求体的作用是什么创建更新资源比如注册需要添加用户数据如何为请求体参数添加类型注解使用py原生的Field注解响应类型默认情况下FastApi会自动将路径操作函数返回的Py对象经jsonable_encode转换为Json格式并包装为JSONresponse返回其他类型相应类型的设置方式1.装饰器指定相应类型场景固定返回类型from fastapi.response import HTMLResponse #返回相应HTML代码 app.get(/html,response_class HTMLResponse) async def get_html(): return h1Helloh12.返回响应类对象场景:文件下载图片流式相应from fastapi import FastApi app.get(/file) async def get_file(): path ./files/1.jpg return FileRespnose(path)3.自定义相应数据各式可以用来约束相应的数据类型class News(BaseModel): id: int title: str content: str app.get(/news/{id},response_modelNews) async def get_news(id: int): return { id: id, title:这是一本书, content:小猪佩奇 }异常处理对于客户端引发的错误应使用fastapi.HTTPException来中断正常处理流程并返回标准错误相应from fastapi improt FastApi,HTTPException app.get(/news/{id}) async def get_news(id: int): id_list [1,2,3,4,5] if id not in id_list: raise HTTPException(status_code404,detail当前id不存在) return {id:id}

相关新闻