0

I work a working API endpoint to create a single user.

@app.post("/entity/", response_model=List[schemas.User])
def create_user(user: schemas.User, db: Session = Depends(get_db)):
    crud.create_user(db=db, user=user)
    return JSONResponse(content={"message": "user created successfully"})

class User(BaseModel):
    id: str = Field(default_factory=generate_id)
    first_name: Optional[str] = ""
    last_name: Optional[str] = ""
    username: str

class Config:
    orm_mode = True

def create_user(db: Session,  user: schemas.User):
    db_item = models.User(**user.dict())
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item

This works, but I want to create multiple Users via one api request.

I guess the create_user function has to look somewhat like this:

def create_user(db: Session, data,  user: schemas.User):
    objects = []
    for user in data:
        db_item = models.User(**user.dict())
        objects.append(dbitem)
    db.bulk_save_objects(objects)
    db.commit()

I just can´t my head around what is the right way to create this kind of bulkinsert

1 Answer 1

2

You can accept a list of users as the request body.

def create_user(db: Session, users: List[schemas.User]):
    objects = []
    for user in users:
        db_item = models.User(**user.dict())
        objects.append(dbitem)
    db.bulk_save_objects(objects)
    db.commit()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.