FastAPI基础入门
第一个FastAPIfromfastapiimportFastAPI# 创建API实例appFastAPI()app.get(/)asyncdefread_root():return{message:Hello FastAPI on PyCharm Community}路由importuvicornfromfastapiimportFastAPI# 创建API实例appFastAPI()app.get(/)asyncdefget_hello():returnhello world参数简介和路径参数importuvicornfromfastapiimportFastAPI# 创建API实例appFastAPI()# 路径参数app.get(/book/{id})asyncdefget_book(id:int):return{id:id,title:f这是第{id}本书}路径参数_Path类型注解importuvicornfromfastapiimportFastAPI,Path# 创建API实例appFastAPI()# 路径参数_path类型注解app.get(/school/{id})asyncdefget_school(id:intPath(...,gt0,lt100,description查询学校的接口)):return{id:id,title:f这是第{id}个学校}# 需求查找书籍的作者路径参数 name长度范围 2 - 10app.get(/user/{id})asyncdefget_name(name:strPath(...,min_length2,max_length10)):return{msg:f这是{name}的信息}查询参数和Query类型注解importuvicornfromfastapiimportFastAPI,Query# 创建API实例appFastAPI()# 查询参数和Query类型注解# http://www.baidu.com?skiplimitapp.get(/news/news_list)asyncdefget_news_list(skip:intQuery(0,description跳过的记录数,lt100),limit:intQuery(10,description返回的记录数)):return{skip:skip,limit:limit}请求体参数importuvicornfromfastapiimportFastAPIfrompydanticimportBaseModel# 创建API实例appFastAPI()# 请求体参数# 注册用户名和密码 - strclassUser(BaseModel):username:strpassword:strapp.post(/register)asyncdefregister(user:User):returnuser请求体参数-Field类型注解importuvicornfromfastapiimportFastAPIfrompydanticimportBaseModel,Field# 创建API实例appFastAPI()# 请求体参数Field类型注解# 注册用户名和密码 - strclassUser(BaseModel):username:strField(张三,min_length2,max_length10,description用户名长度要求2-10个字)password:strField(min_length3,max_length20)app.post(/register)asyncdefregister(user:User):returnuser响应参数-JSON格式importuvicornfromfastapiimportFastAPI# 创建API实例appFastAPI()# 响应格式-JSONapp.get(/response_json)asyncdefget_response_json():return{message:hello world}响应参数-HTML格式importuvicornfromfastapiimportFastAPIfromstarlette.responsesimportHTMLResponse,FileResponse# 创建API实例appFastAPI()# 响应格式-HTMLapp.get(/response_html,response_classHTMLResponse)asyncdefget_html():returnh1这是一级标题/h1响应参数-文件格式# 响应格式-文件类型importuvicornfromfastapiimportFastAPIfromstarlette.responsesimportHTMLResponse,FileResponse# 创建API实例appFastAPI()# 返回一张图片内容app.get(/response_file)asyncdefget_file():path./files/1.jpegreturnFileResponse(path)自定义响应格式importuvicornfromfastapiimportFastAPIfrompydanticimportBaseModel,Fieldfromstarlette.responsesimportHTMLResponse,FileResponse# 创建API实例appFastAPI()# 需求新闻接口 - 响应数据格式 id、title、contentclassNews(BaseModel):id:inttitle:strcontent:strapp.post(/news/{id},response_modelNews)asyncdefget_news(id:int):return{id:id,title:f这是第{id}本书,content:这是一本好书}异常响应处理importuvicornfromfastapiimportFastAPI,HTTPException# 创建API实例appFastAPI()# 异常响应处理# 需求按id新闻查询 - 1 - 6app.get(/get/exc/news/{id})asyncdefget_exc_news(id:int):id_list[1,2,3,4,5,6]ifidnotinid_list:raiseHTTPException(status_code404,detail您查找的新闻不存在)return{id:id}