FASTAPI 03-带参数的URL请求

FASTAPI系列 03-带参数的URL请求


前言

在开发一个restful接口时,我们会对接口请求传递参数,例如:

查询联系人person信息接口,请求方式get,请求地址:/api/person/{id}

删除联系人person信息接口, 请求方式delete, 请求地址:/api/person/{id}

在请求接口地址中,{id} 就是路径中的参数

一、示例

声明一个查询联系人信息的get请求,编写该接口,代码如下:

from fastapi import FastAPI

# 导入FastAPI模块并创建一个FastAPI实例
app = FastAPI()
# 使用装饰器@app.get("/second/{id}")定义一个GET请求处理函数(endpoint)
# 当用户访问应用的根路径 "/second{id}" 时,get_person_info函数会被调用
@app.get("/second/{id}")
async def get_person_info(id: int) -> dict:
    # 请求路径中的id值作为参数传入到该函数
    # 函数返回一个字典,内容{"name": "Teacher Li", "id": id},带入id的值
    # 这个字典会被自动转换成JSON格式返回给客户端
    return {"name": "Teacher Li", "id": id}

二、使用步骤

启动服务,在浏览器中输入 http://127.0.0.1:8000/second/1,会返回
在这里插入图片描述

2. 请求参数类型

在我们的代码中,已经规定了请求参数的id只能传int类型,如果在浏览器中访问时,我们请求参数传成string类型,将会发生什么呢?我们接下来试试吧!

返回代码(示例):

{
	"detail":[
		{
			"type":"int_parsing",
			"loc":[
					"path",
					"id"
					],
			"msg":"Input should be a valid integer, unable to parse string as an integer",
			"input":"\"1\"",
			"url":"https://errors.pydantic.dev/2.6/v/int_parsing"
		}
	]
}

它会告诉你,你path请求的参数为int, 输入的参数不是一个integer;


Docs文档

你会发现,在docs里面,已经表明id是必须传的参数,类型为integer,下面让我们通过API的交互,来试试吧;

在这里插入图片描述
我们可以清晰的看到,传入id为999后,返回的报文为

{"name": "Teacher Li", "id": 999}

在这里插入图片描述

总结

文章通过实例阐述了FastAPI框架下如何便捷、严格地处理URL路径参数,并利用自动化的API文档增强接口使用的可理解和可测试性。

更多内容,请关注公众号

在这里插入图片描述

了解更多,请加入QQ群:5771098

在这里插入图片描述

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在FastAPI中进行重定向并携参数,可以使用FastAPI的内置函数`fastapi.responses.RedirectResponse`。以下是一个示例代码: ```python from fastapi import FastAPI, Response from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/redirect") async def redirect_with_param(param: str): url = f"/new_location?param={param}" response = RedirectResponse(url) return response @app.get("/new_location") async def new_location(param: str): return {"param": param} ``` 在上面的示例代码中,`redirect_with_param`函数接收一个名为`param`的查询参数并创建一个URL,其中包含该参数。然后,该函数使用`RedirectResponse`函数将请求重定向到新URL。最后,新请求将由`new_location`函数处理,该函数接收`param`参数并将其返回给客户端。 请注意,如果您使用的是FastAPI 0.63.0或更高版本,您还可以使用`url_for`函数来创建URL,如下所示: ```python from fastapi import FastAPI, Response, url_for from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/redirect") async def redirect_with_param(param: str): url = url_for("new_location", param=param) response = RedirectResponse(url) return response @app.get("/new_location") async def new_location(param: str): return {"param": param} ``` 在这个示例中,`url_for`函数接收目标路由函数的名称和其接收的参数,并生成一个包含参数URL。然后,`RedirectResponse`函数使用该URL来创建重定向响应。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值