Ken Hsieh
Ken Hsieh

Reputation: 75

Define a Request parameter as an optional variable type in fastapi

I would like to define a Request object as an optional variable type in FastAPI, but I got an error:

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that typing.Optional[starlette.requests.Request] is a valid pydantic field type

Here is the code:

from fastapi import APIRouter, Request
from typing import Optional, Union
import starlette
    
router = APIRouter(
    tags=['pcinfo'],
    prefix='/api/v1',
    responses={404: {'message': 'Not found'}}
)
    
@router.get('/pcinfo/', tags=['pcinfo'])
def get_users(req: Optional[Request] = None):
    if req:
        print(type(req))
        print(req.query_params)
        para = dict(req.query_params)
        return para
    else:
        print(req)
        return {'message': 'hello'}

And then I imported starlette and changed the Optional[Request] to Optional[starlette.requests.Request] but it still showed the same error message.

Upvotes: 2

Views: 6991

Answers (2)

Pradeep
Pradeep

Reputation: 31

You can pass the request object as optional like below

import starlette
@app.api_route("/endpoint/v1/{my_id}", methods=["GET", "POST", "DELETE"])
async def myFunction(request : starlette.requests.Request = None): 

Upvotes: 1

Paul P
Paul P

Reputation: 3907

If you would like to add optional query parameters, you can simply declare them as arguments to the (path operation) function handling the endpoint (see FastAPI docs), e.g.:

@router.get('/pcinfo/', tags=['pcinfo'])
def get_users(
  query_param_1: Optional[int] = None,
  query_param_2: Optional[str] = None,
):
    if query_param_1:
        print(query_param_1)

    if query_param_2:
        print(query_param_2)

    if query_param_1 or query_param_2:
        return {
            "query_param_1": query_param_1,
            "query_param_2": query_param_2,
        }

    if not query_param_1 and not query_param_2:
        return {'message': 'hello'}

If you'd like to get the query parameters as a dict, you could follow the approach described in the FastAPI docs, e.g.:

async def query_params(param1: Optional[int] = None, param2: Optional[str] = None):
    return {"param1": param1, "param2": param2}

@router.get('/pcinfo/', tags=['pcinfo'])
def get_users(query_params: dict = Depends(query_params)):

    if query_params["param1"]:
        print(query_params["param1"])

    if query_params["param2"]:
        print(query_params["param2"])

    # <your logic here>

Upvotes: 3

Related Questions