FastAPI基础入门

FastAPI基础入门

第一个FastAPI

fromfastapiimportFastAPI# 创建API实例app=FastAPI()@app.get("/")asyncdefread_root():return{"message":"Hello FastAPI on PyCharm Community"}

路由

importuvicornfromfastapiimportFastAPI# 创建API实例app=FastAPI()@app.get("/")asyncdefget_hello():return"hello world"

参数简介和路径参数

importuvicornfromfastapiimportFastAPI# 创建API实例app=FastAPI()# 路径参数@app.get("/book/{id}")asyncdefget_book(id:int):return{"id":id,"title":f"这是第{id}本书"}

路径参数_Path类型注解

importuvicornfromfastapiimportFastAPI,Path# 创建API实例app=FastAPI()# 路径参数_path类型注解@app.get("/school/{id}")asyncdefget_school(id:int=Path(...,gt=0,lt=100,description="查询学校的接口")):return{"id":id,"title":f"这是第{id}个学校"}# 需求,查找书籍的作者,路径参数 name,长度范围 2 - 10@app.get("/user/{id}")asyncdefget_name(name:str=Path(...,min_length=2,max_length=10)):return{"msg":f"这是{name}的信息"}

查询参数和Query类型注解

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

请求体参数

importuvicornfromfastapiimportFastAPIfrompydanticimportBaseModel# 创建API实例app=FastAPI()# 请求体参数# 注册:用户名和密码 -> strclassUser(BaseModel):username:strpassword:str@app.post("/register")asyncdefregister(user:User):returnuser

请求体参数-Field类型注解

importuvicornfromfastapiimportFastAPIfrompydanticimportBaseModel,Field# 创建API实例app=FastAPI()# 请求体参数Field类型注解# 注册:用户名和密码 -> strclassUser(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")asyncdefregister(user:User):returnuser

响应参数-JSON格式

importuvicornfromfastapiimportFastAPI# 创建API实例app=FastAPI()# 响应格式-JSON@app.get("/response_json")asyncdefget_response_json():return{"message":"hello world"}

响应参数-HTML格式

importuvicornfromfastapiimportFastAPIfromstarlette.responsesimportHTMLResponse,FileResponse# 创建API实例app=FastAPI()# 响应格式-HTML@app.get("/response_html",response_class=HTMLResponse)asyncdefget_html():return"<h1>这是一级标题</h1>"

响应参数-文件格式

# 响应格式-文件类型importuvicornfromfastapiimportFastAPIfromstarlette.responsesimportHTMLResponse,FileResponse# 创建API实例app=FastAPI()# 返回一张图片内容@app.get("/response_file")asyncdefget_file():path="./files/1.jpeg"returnFileResponse(path)

自定义响应格式


importuvicornfromfastapiimportFastAPIfrompydanticimportBaseModel,Fieldfromstarlette.responsesimportHTMLResponse,FileResponse# 创建API实例app=FastAPI()# 需求:新闻接口 -> 响应数据格式 id、title、contentclassNews(BaseModel):id:inttitle:strcontent:str@app.post("/news/{id}",response_model=News)asyncdefget_news(id:int):return{"id":id,"title":f"这是第{id}本书","content":"这是一本好书"}

异常响应处理

importuvicornfromfastapiimportFastAPI,HTTPException# 创建API实例app=FastAPI()# 异常响应处理# 需求:按id新闻查询 -> 1 - 6@app.get("/get/exc/news/{id}")asyncdefget_exc_news(id:int):id_list=[1,2,3,4,5,6]ifidnotinid_list:raiseHTTPException(status_code=404,detail="您查找的新闻不存在")return{"id":id}