7天掌握FastAPI-参数
1.6.1分析同一段接口逻辑根据参数不同返回不同的数据1.6.2介绍参数就是客户端发送请求时附带的额外信息和指令参数的作用是让同一个接口能根据不同的输入返回不同的输出实现动态交互1.6.3参数分类1.6.3.1路径参数Path Parameter位置URL 路径的一部分格式为 /资源/{参数名}如 /book/{id}。作用指向唯一的、特定的资源如获取某本具体书籍的信息。常用方法GET用于获取资源。app.get(/book/{id}) # 定义请求的的路径请求方式为get async def get_book(id: int): # 定义这个接口接收一个参数id数据类型为int # 返回响应结果 return {id: id, title: f这是第{id}本书}---运行后查看旁边的运行结果接口文档中进行测试注意这里进行参数调试的时候必须填一个值否则直接excute会报错1.6.3.1.1类型注解PathFastAPI 允许为参数声明额外的信息和校验app.get(/book/{id}) async def get_book(id: int): return {id: id, title: f这是第{id}本书}1.6.3.1.2导入 FastAPI 的 Path 函数app.get(/book/{id}) async def get_book(id: int Path()): return {id: id, title: f这是第{id}本书}# 定义请求的的路径请求方式为get app.get(/book/{id}) # 定义这个接口接收一个参数id数据类型为int async def get_book(id: intPath(...,gt0,lt101)): # 返回响应结果 return {id: id, title: f这是第{id}本书}重启然后找到接口填写1111.6.3.1.3会发现报错了id要求不能大于101,# 定义请求的的路径请求方式为get app.get(/book/{id}) # 定义这个接口接收一个参数id数据类型为int async def get_book(id: intPath(...,gt0,lt101,description书籍id取值范围为1-100)): # 返回响应结果 return {id: id, title: f这是第{id}本书}# 需求查找书籍的作者路径参数 name长度范围 2-10 app.get(/book/{name}) async def get_name(name: str Path(..., min_length2, max_length10, description书籍名称长度范围为2-10)): return {msg: f这是{name}的信息}1.6.3.1.4小结路径参数出现在什么位置URL 路径的一部分如何为路径参数添加类型注解Python 原生注解 和 Path 注解1.6.3.1.5练习需求定义两个接口携带路径参数并使用 Path 来实现类型注解具体如下接口1以 新闻分类 id 为参数设计 URLid 范围为 1 ~ 100接口2以 新闻分类名称为参数设计 URL分类名称长度为 2 ~ 10from fastapi import FastAPI, Path app FastAPI() # --------------------------------------------------------- # 接口1新闻分类 ID # 需求id 范围为 1 ~ 100 # URL 示例: /news/category/50 # --------------------------------------------------------- app.get(/news/category/{category_id}) async def get_news_by_id( category_id: int Path( ..., title新闻分类ID, description新闻分类的唯一标识符, ge1, # 大于等于 1 le100 # 小于等于 100 ) ): return {category_id: category_id, message: 成功获取该分类下的新闻} # --------------------------------------------------------- # 接口2新闻分类名称 # 需求分类名称长度为 2 ~ 10 # URL 示例: /news/search/科技 # --------------------------------------------------------- app.get(/news/search/{category_name}) async def get_news_by_name( category_name: str Path( ..., title新闻分类名称, description新闻分类的名称关键字, min_length2, # 最小长度 2 max_length10 # 最大长度 10 ) ): return {category_name: category_name, message: 成功搜索该分类相关的新闻}1.6.3.2查询参数Query Parameter位置URL 中 ? 之后格式为 key1value1key2value2如 ?page1sortdesc。作用对资源集合进行过滤、排序、分页等操作如查询“第1页、按时间降序”的书籍列表。常用方法GET用于获取资源集合的筛选结果。声明的参数不是路径参数时路径操作函数会把该参数自动解释为查询参数在news_list后面拼接参数如右图# 需求查询新闻页-分页skip跳过的记录数limit返回的记录数 10 app.get(/news/news_list) async def get_news_list(skip: int, limit: int 10): return {skip: skip, limit: limit}1.6.3.2.1类型注解 Query导入 FastAPI 的 Query 函数# 需求查询新闻页-分页skip跳过的记录数limit返回的记录数 10 app.get(/news/news_list) async def get_news_list( skip: int Query(0, description跳过的记录数,lt100), limit: int Query(10, description返回的记录数,lt100) ): return {skip: skip, limit: limit}1.6.3.2.2小结查询参数出现在什么位置URL? 之后 k1v1k2v2如何为查询参数添加类型注解Python 原生注解 和 Query 注解1.6.3.2.3练习需求设计接口查询图书要求携带两个查询参数图书分类和价格参数具体要求图书分类默认值为 Python开发长度限制5 ~ 255价格限制大小范围 50 ~ 100from fastapi import FastAPI, Query app FastAPI() app.get(/books/) async def read_books( # 需求图书分类默认值为 Python开发长度限制 5 ~ 255 category: str Query( Python开发, min_length5, max_length255, description图书的分类名称 ), # 需求价格限制大小范围 50 ~ 100 price: float Query( ..., ge50, le100, description图书的价格范围 ) ): return { category: category, price: price, message: 查询成功 }1.6.3.3请求体Request Body位置HTTP 请求的消息体body中常以 JSON 等格式携带数据。作用用于创建、更新资源或携带大量数据如提交书籍的详细信息、更新用户资料。常用方法POST创建资源、PUT更新资源等。在HTTP协议中一个完整的请求由三部分组成① 请求行包含方法、URL、协议版本② 请求头元数据信息Content-Type、Authorization等③ 请求体实际要发送的数据内容1.6.3.3.1定义类型from pydantic import BaseModel class User(BaseModel): username: str password: str类型注解app.post(/register) async def register(user: User): return user响应结果如下1.6.3.3.2练习需求设计接口新增图书图书信息包含书名、作者、出版社、售价from fastapi import FastAPI from pydantic import BaseModel from typing import Optional app FastAPI() # 1. 定义数据模型 (Pydantic Model) class BookItem(BaseModel): title: str # 书名 author: str # 作者 publisher: str # 出版社 price: float # 售价 # 2. 定义新增图书接口 app.post(/books/, summary新增图书) async def create_book(book: BookItem): 接收 JSON 格式的图书信息并返回 # 这里通常会写数据库插入逻辑 return { message: 图书新增成功, book_info: book }1.6.3.3.3类型注解 Field导入 pydantic 的Field函数from pydantic import BaseModel, Field class User(BaseModel): username: str Field(...) password: str Field(...)# 注册用户名和密码-str class User(BaseModel): username: str Field(default张三, min_length2, max_length10, description用户名长度范围为2-10) password: str Field(min_length6, max_length20, description密码长度范围为6-20) app.post(/register) async def register(user: User): return user1.6.3.3.4小结请求体参数的作用是什么创建、更新资源如何定义、使用请求体参数# 注册用户名和密码-str class User(BaseModel): username: str Field(default张三, min_length2, max_length10, description用户名长度范围为2-10) password: str Field(min_length6, max_length20, description密码长度范围为6-20) app.post(/register) async def register(user: User): return user如何为请求体参数添加类型注解Python 原生注解 和 Field 注解1.6.3.3.5练习需求设计接口新增图书图书信息包含书名、作者、出版社、售价具体要求如下 书名不能为空长度 2 ~ 20 作者长度 2 ~ 10 出版社默认值“黑马出版社” 售价不能为空价格大于0元from fastapi import FastAPI from pydantic import BaseModel, Field from typing import Optional app FastAPI() # 1. 定义数据模型 class Book(BaseModel): # 书名不能为空长度 2 ~ 20 book_name: str Field( ..., min_length2, max_length20, description书名必填2-20字 ) # 作者长度 2 ~ 10 author: str Field( ..., min_length2, max_length10, description作者必填2-10字 ) # 出版社默认值“黑马出版社” publisher: str Field( default黑马出版社, description出版社默认黑马出版社 ) # 售价不能为空价格大于0元 price: float Field( ..., gt0, description价格必填大于0 ) # 2. 定义新增图书接口 app.post(/books, summary新增图书) async def create_book(book: Book): 接收图书信息校验通过后返回 # 这里可以添加保存到数据库的逻辑 return {message: 图书新增成功, book_data: book}1.6.3.3.4核心区别总结完整代码from fastapi import FastAPI, Path, Query from pydantic import BaseModel,Field # 创建FastAPI实例 app FastAPI() app.get(/) async def root(): return {message: Hello World 666} app.get(/hello/{name}) async def say_hello(name: str): return {message: fHello {name}} # 访问/hello响应结果 msg你好 FastAPI app.get(/hello) async def get_hello(): return {msg: 你好 FastAPI} app.get( /user/hello) async def get_user_hello(): return {msg: 我正在学习 FastAPI ......} # 定义请求的的路径请求方式为get app.get(/book/{id}) # 定义这个接口接收一个参数id数据类型为int async def get_book(id: int Path(..., gt0, lt101, description书籍id取值范围为1-100)): # 返回响应结果 return {id: id, title: f这是第{id}本书} # 需求查找书籍的作者路径参数 name长度范围 2-10 app.get(/book/{name}) async def get_name(name: str Path(..., min_length2, max_length10, description书籍名称长度范围为2-10)): return {msg: f这是{name}的信息} # 需求查询新闻页-分页skip跳过的记录数limit返回的记录数 10 app.get(/news/news_list) async def get_news_list( skip: int Query(0, description跳过的记录数,lt100), limit: int Query(10, description返回的记录数,lt100) ): return {skip: skip, limit: limit} # 注册用户名和密码-str class User(BaseModel): username: str Field(default张三, min_length2, max_length10, description用户名长度范围为2-10) password: str Field(min_length6, max_length20, description密码长度范围为6-20) app.post(/register) async def register(user: User): return user
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2590737.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!