FastAPI Query Parameters Made Simple

FastAPI Query Parameters Made Simple

What is Query String in FastAPI call?

A query string in fastapi is formed by key=value pairs which are joined by “&” character. For example:

http://localhost:8000/home?name=Sanjana &age=20

Here, when the fastAPI parser see question mark, it considers anything followed by question mark as the query parameter then it bifurcates the query parameter on the basis of ‘&’ by key-value pair. Then their key value pairs are passed to the method which is followed by decorator.

Below are the steps performed by fastAPI parser to resolve path parameter and query string for given call http://localhost:8000/home?name=Sanjana &age=20 and given endpoint decorator method

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/home/{name}/{age}")
async def hello(name:str,age:int):
   return {"name": name, "age":age}
  1. When the parser encounter like above it will first check for path parameter, here it will consider anything the followed after port will be considered as path parameter till it get something like “?” character.
  2. Then it will check for “?” and anything which proceed by “?” will be considered as query parameter.
  3. So, the path parameter and query parameter for our example would
    1. Path Parameter: home
    1. Query Parameter: {name: Sanjana, age:20}
  4. Now it will try to find the decorator method which has endpoint as home and decorator method takes two arguments as name and age, the valid decorator method would be picked in our case would be:
    • @app.get(“/home”)
    • async def hello(name:str,age:int)

Learn with the help of example:

We are creating three get method

  1. Root end point method
  2. Only query parameter
  3. Path Parameter plus query Parameter

Complete Program:

from fastapi import FastAPI

app = FastAPI()


@app.get("/home")
async def hello():
    return {"first_message": "Hello from Elfin"}


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


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

Home end point

@app.get("/home")
async def hello():
    return {"first_message": "Hello from Elfin"}

Here there is neither path parameter or query parameter, it is being called by simple http call like below:

http://127.0.0.1:8000/home

And the response would be:

{
  "first_message": "Hello from Elfin"
}

Only Query Parameter:

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

Here there is no path parameter, but the decorator method hello(name:star, age: int) takes two parameter, so the call made to such query parameter would be like

http://127.0.0.1:8000/person?name=Harsha&age=20

and the response would be:

{
  "name": "Harsha",
  "age": 20
}

Path Parameter plus Query Parameter:

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

In this case we have both path parameter as name and query parameter as age, the call to the decorator method would be like this:

http://127.0.0.1:8000/person/Harsha?age=20

where “Harsha” would be the path parameter and “?age=20” is the query parameter, the response output would be

{
  "name": "Harsha",
  "age": 20
}

Swagger UI for above methods would be:

Test Cases for above query parameter decorator methods

from fastapi.testclient import TestClient
from query_parameter import app
import pytest

client = TestClient(app)


def test_case1():
    response = client.get("/home")
    assert response.status_code == 200
    assert response.json() == {"first_message": "Hello from Elfin"}


def test_case2():
    print('a')
    response = client.get("/person?name=Harsha&age=20")
    assert response.status_code == 200
    assert response.json() == {"name": "Harsha", "age": 20}


def test_case3():
    print('a')
    response = client.get("/person/Harsha?age=20")
    assert response.status_code == 200
    assert response.json() == {"name": "Harsha", "age": 20}

Leave a Reply

Your email address will not be published. Required fields are marked *