How to have fastcrud routes with some parameters in path arguments? #262
nimitbhardwaj
started this conversation in
General
Replies: 1 comment
-
|
You can handle nested resource CRUD in FastCRUD using the Option 1: Use path parameters in endpoint definitions from fastcrud import crud_router
# Your models
class School(SQLModel, table=True):
id: int | None = Field(primary_key=True)
name: str
class Class(SQLModel, table=True):
id: int | None = Field(primary_key=True)
name: str
school_id: int = Field(foreign_key="school.id")
# Create the router with path parameter
class_router = crud_router(
session=get_session,
model=Class,
create_schema=ClassCreate,
update_schema=ClassUpdate,
path="/api/schools/{school_id}/classes",
tags=["classes"]
)Option 2: Use operation-specific dependencies to inject school_id from fastapi import Path, Depends
def get_school_context(school_id: int = Path(...)):
return {"school_id": school_id}
class_router = crud_router(
session=get_session,
model=Class,
create_schema=ClassCreate,
update_schema=ClassUpdate,
path="/api/schools/{school_id}/classes",
create_deps=[get_school_context],
update_deps=[get_school_context]
)Option 3: Custom create endpoint with automatic school_id injection from fastapi import Body, Path, Depends
from sqlalchemy.ext.asyncio import AsyncSession
@class_router.post("")
async def create_class(
school_id: int = Path(...),
class_data: ClassCreate = Body(...),
db: AsyncSession = Depends(get_session)
):
# Automatically add school_id to the data
create_data = class_data.model_dump()
create_data["school_id"] = school_id
return await fastcrud.create(db, Class, create_data)The |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Suppose I have CRUD paths such as below
where I want to create the CRUD methods for classes in context of school. For the create data call, I would want data similar to like below.
but in the DB, we would also be storing the name and school ID for the class table, class has a foreign key to school. So for these type of cases, how can I use fastCrud or crud_router.
Beta Was this translation helpful? Give feedback.
All reactions