How to add a pydantic class as a dependency for a GET route?
See original GitHub issueI want to have a GET route that returns the schema of a pydantic class. This way the frontend can call the get route and can build a form that then posts to the post route. A simple version could be:
class GenerationOptions(BaseModel):
model: str
truncation: float
@router.post("/generate")
def generate_image(model: GenerationOptions):
return something
@router.get("/generate")
def generate_image(model: dict = Depends(GenerationOptions.schema))): # doesn't work
return {"form_fields": model}
However, this doesn’t work. The only way I can achieve what I want is with another function:
class GenerationOptions(BaseModel):
model: str
truncation: float
@router.post("/generate")
def generate_image(model: GenerationOptions):
return something
def getSomething():
return GenerationOptions.schema()
@router.get("/generate")
def generate_image(model: dict = Depends(getSomething)):
return {"form_fields": model}
This works but I think that there might be another/better solution. Any ideas? Thanks!
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (1 by maintainers)
Top Results From Across the Web
Settings management - pydantic
Create a clearly-defined, type-hinted application configuration class; Automatically read modifications to the configuration from environment variables ...
Read more >[FEATURE] Use pydantic's BaseModel as dependency with ...
I wish to use pydantic's BaseModel with validators as depency injection. Classes as dependencies are handy because I can fuse multiple path/body ...
Read more >FastAPI - GET Request with Pydantic List field - Stack Overflow
Show activity on this post. from fastapi import APIRouter,Depends, Query from pydantic import BaseModel from typing import Optional,List router ...
Read more >Classes as Dependencies - FastAPI
If you pass a "callable" as a dependency in FastAPI, it will analyze the parameters for that "callable", and process them in the...
Read more >Dependency Injection - Starlite
from starlite import Controller, Router, Starlite, Provide, get def bool_fn() ... Dependencies are callables - sync or async functions, methods or class ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Mostly because the dependency injection makes it easier to test the route.
My approach now is this:
I am not sure if this is the best way to do this but this works perfectly for my case.