English 中文(简体)
FastAPI - Query Parameters
  • 时间:2024-12-22

FastAPI - Query Parameters


Previous Page Next Page  

A classical method of passing the request data to the server is to append a query string to the URL. Assuming that a Python script (hello.py) on a server is executed as CGI, a pst of key-value pairs concatenated by the ampersand (&) forms the query string, which is appended to the URL by putting a question mark (?) as a separator. For example −

http://localhost/cgi-bin/hello.py?name=Ravi&age=20

The traipng part of the URL, after (?), is the query string, which is then parsed by the server-side script for further processing.

As mentioned, the query string is a pst of parameter=value pairs concatenated by & symbol. FastAPI automatically treats the part of the endpoint which is not a path parameter as a query string and parses it into parameters and its values. These parameters are passed to the function below the operation decorator.

Example


from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
async def hello(name:str,age:int):
   return {"name": name, "age":age}

Start the Uvicorn server and this URL in the browser −

http://localhost:8000/hello?name=Ravi&age=20

You should get the same JSON response. However, checking the tells you that FastAPI has detected that /hello endpoint has no path parameters, but query parameters.

FastAPI Query Parameters

Cpck the Try it out button, enter "Ravi" and "20" as values, and press the Execute button. The documentation page now shows Curl command, request URL, and the body and headers of HTTP response.

FastAPI Query Parameters

Example

You can use Python’s type hints for the parameters of the function to be decorated. In this case, define name as str and age as int.


from fastapi import FastAPI
app = FastAPI()
@app.get("/hello/{name}")
async def hello(name:str,age:int):
   return {"name": name, "age":age}

Try entering http://localhost:8000/docs as the URL. This will open the Swagger UI (OpenAPI) documentation. The parameter name is a path parameter and age is a query parameter

FastAPI Query Parameters Advertisements