How to Pass Query Parameters in FastAPI

Posted by


In FastAPI, passing query parameters allows you to receive data from the client in the URL as key-value pairs. Query parameters are appended to the end of the URL and separated by a question mark "?". They are useful for filtering, sorting, or paginating data.

Let’s create a simple FastAPI application to demonstrate how to pass query parameters. First, you will need to install FastAPI and Uvicorn using pip:

pip install fastapi uvicorn

Next, create a new Python file (e.g., app.py) and import FastAPI:

from fastapi import FastAPI

Then, create an instance of the FastAPI class:

app = FastAPI()

Now, let’s define a route that accepts query parameters. Create a new endpoint that takes two query parameters, name and age:

@app.get("/user")
async def get_user(name: str, age: int):
    return {"name": name, "age": age}

In this example, the get_user function defines two parameters, name and age, which correspond to the query parameters in the URL. The str and int types specify the expected data types for each parameter.

To run the FastAPI application, use Uvicorn:

uvicorn app:app --reload

Now, you can access the endpoint using a web browser or a tool like cURL. For example, to pass the query parameters "John" as the name and "30" as the age, you can visit the following URL:

http://localhost:8000/user?name=John&age=30

The response will be a JSON object containing the values of the query parameters:

{"name": "John", "age": 30}

You can also access query parameters using third-party tools like Postman or curl. For example, using curl from the terminal:

curl 'http://localhost:8000/user?name=Jane&age=25'

This will return the following JSON response:

{"name": "Jane", "age": 25}

In addition to simple scalar types, you can also use more complex types like lists or dictionaries as query parameters. For example, you could modify the get_user endpoint to accept a list of hobbies as a query parameter:

@app.get("/user")
async def get_user(name: str, age: int, hobbies: List[str] = []):
    return {"name": name, "age": age, "hobbies": hobbies}

Now, you can pass a list of hobbies in the query parameters:

http://localhost:8000/user?name=Alice&age=28&hobbies=reading&hobbies=hiking

The response will include the hobbies as a list:

{"name": "Alice", "age": 28, "hobbies": ["reading", "hiking"]}

In conclusion, passing query parameters in FastAPI is a simple and intuitive way to send data to your API endpoints. By defining parameters in your route functions, you can access and process query parameters easily. Remember to specify data types for each parameter to ensure type safety and handle optional parameters using default values. Happy coding!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@chuttyboycreation
1 month ago

How to connect this with react js and get values and stored them in this prameter ????