This is the third day of my participation in the August Text Challenge.More challenges in August
What are query parameters?
In FastApi, when you declare other function parameters that are not path parameters, they are automatically interpreted as “query string” parameters.
The sample code
from fastapi import FastAPI
import uvicorn
app = FastAPI()
goods=['xiaomi'.'apple'.'huawei'.'oppo']
@app.get('/goods/')
async def get_goods(start:int = 0,end:int = 3) :
return goods[start:end]
if __name__ == "__main__":
uvicorn.run(app='main:app',host='0.0.0.0',reload=True,debug=True)
Copy the code
The interface test
With parameters
Band partial parameter
Since both query parameters have default values in the view function behind the scenes, we can test the request by modifying individual parameters.
Use default parameters
When we send a request without query parameters, the background will use the default parameters to process the request after receiving it. Start =1, end=3
Optional parameters
In our actual development, some parameters may or may not be required, depending on the needs of users.
The sample code
@app.get('/name/{name}/age/{age}')
async def get_userinfo(name:str,age:int,j:Optional[bool] =False) :
ret = {'Name':name}
if j:
ret.update({'Age':age})
return ret
Copy the code
Age is not returned by default. When j is true, age information is returned.
The interface test
A normal request that does not return age information by default
A request with parameter j returns age information
Parameter type conversion
As mentioned above, when we carry the parameter j for the request, its value is True. FastApi provides us with a more convenient way to query the parameter type conversion, that is, when its value is any True value, the request processing can be completed.
The sample request
Request operation at j=1
Request operation at j=0
This parameter is mandatory
In real development, we might need the user to carry a parameter to complete the request.
code
All we need to do is add a parameter q to the code above and FastApi will do the rest for us.
@app.get('/name/{name}/age/{age}')
async def get_userinfo(name:str,age:int,q:bool,j:Optional[bool] =False) :
ret = {'Name':name}
if j:
ret.update({'Age':age})
return ret
Copy the code
The interface test
When a request is made without q
Prompt Query parametersq
missing
Request with q parameter
The request is successful
Thank you for reading, don’t forget to follow, like, comment, forward four consecutive yo!