question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Using pydantic models for GET request query params? Currently not possible, have to use dataclasses or normal classes.

See original GitHub issue

Description

Is there a way to use pydantic models for GET requests? I would like to have a similar interface for both query params and for the body. So for instance, an example could look like this:

class PingArgs(BaseModel):
    """Model input for PingArgs."""

    dt: datetime.datetime = ...
    to_sum: List[int] = ...

    @validator("dt", pre=False, always=True, whole=True)
    def validate_dt(cls, v, values):
        """Validate dt."""
        parsed_dt = v.replace(tzinfo=None)
        return parsed_dt

@router.get("/ping", tags=["basic"])
def ping(args: PingArgs, request: Request):
    """Example."""
    return JSONResponse(
        status_code=starlette.status.HTTP_200_OK,
        content={"detail": "pong", "dt": args.dt.isoformat() "summed": sum(x for x in args.to_sum)},
    )

Where as, right now I think you would have to do something like this:

@router.get("/ping", tags=["basic"])
def ping(dt: datetime.datetime = Query(None), to_sum: List[int] = Query(None), request: Request):
    """Example."""
    parsed_dt = dt.replace(tzinfo=None)
    
    return JSONResponse(
        status_code=starlette.status.HTTP_200_OK,
        content={"detail": "pong", "dt": dt.isoformat() "summed": sum(x for x in to_sum)},
    )

Hope this can be clarified.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:25
  • Comments:42 (9 by maintainers)

github_iconTop GitHub Comments

20reactions
tiangolocommented, Jun 30, 2019

@LasseGravesen You would do it like this:

from fastapi import FastAPI, Depends, Query

app = FastAPI()


class SearchArgs:
    def __init__(
        self,
        query: str = Query(...),
        limit: int = Query(10),
        offset: int = Query(0),
        sort: str = Query("date"),
    ):
        self.query = query
        self.limit = limit
        self.offset = offset
        self.sort = sort


@app.get("/api/v1/search_dataclass", tags=["basic"])
def search(args: SearchArgs = Depends()):
    return {"detail": "search-result", "args": args, "results": {"abc": "def"}}

Check the docs here: https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/

15reactions
jimcarreercommented, Feb 1, 2020

This is an older issue but I wanted to show my solution to this problem:

class PagingQuery(BaseModel):
    page: conint(ge=1)
    page_size: conint(ge=1, le=250) = 50

    @classmethod
    async def depends(cls, page: int = 1, page_size: int = 50):
        try:
            return cls(page=page, page_size=page_size)
        except ValidationError as e:
            errors = e.errors()
            for error in errors:
                error['loc'] = ['query'] + list(error['loc'])
            raise HTTPException(422, detail=errors)


@app.get("/example", tags=["basic"])
def example(paging: PagingQuery = Depends(PagingQuery.depends)):
    return {"page": paging.page, "page_size": paging.page_size}

I don’t know if this helps anyone / solves the problem but it does allow you to use pydantic validation for query parameters and get similar error responses to payload validation failure.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI - GET Request with Pydantic List field - Stack Overflow
When you declare a List field in the Pydantic model, it is interpreted as a request body parameter, instead of a query one...
Read more >
Using Dataclasses - FastAPI
Using Dataclasses ¶. FastAPI is built on top of Pydantic, and I have been showing you how to use Pydantic models to declare...
Read more >
Pydantic V2 Plan
pydantic -core operates on a tree of validators with no "model" type required at the base of that tree. It can therefore validate...
Read more >
Pydantic or dataclasses? Why not both? Convert Between Them
To get the information we need for the pydantic model, we use the fields utility ... We can check if the class is,...
Read more >
Any reason not to use dataclasses everywhere? : r/Python
Absolutely use data classes when they do the job. Cases when this is not true (or it's awkward):. custom init method. custom new...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found