I'm making simple CRUD API using FastAPI and what I want to do is generate unique random when creating new item (other fields are address and name which should be filled by user). How can I do that?
There is fragment of my code with class and a POST function.
app = FastAPI()
userdb = []
class User(BaseModel):
id: int
address: str
name: str
@app.post("/users")
def add_user(user: User):
userdb.append(users.dict())
return userdb[-1]
uuid4 is often the way to go
It'll be absolutely unique amongst any id ever generated with the function anywhere with astronomical likelihood (refer to RFC-4122 Section 4.4) and is very fast
from uuid import uuid4
...
unique_id = str(uuid4())
Another option - often what you want is for this ID to not necessarily be random, but rather to be some auto-incremented index from your database. The FastAPI docs give an example of this:
...
notes = sqlalchemy.Table(
"notes",
metadata,
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column("text", sqlalchemy.String),
sqlalchemy.Column("completed", sqlalchemy.Boolean),
)
...
class NoteIn(BaseModel):
text: str
completed: bool
class Note(BaseModel):
id: int
text: str
completed: bool
...
@app.post("/notes/", response_model=Note)
async def create_note(note: NoteIn):
query = notes.insert().values(text=note.text, completed=note.completed)
last_record_id = await database.execute(query)
return {**note.dict(), "id": last_record_id}
https://fastapi.tiangolo.com/advanced/async-sql-databases/?h=id#about-notedict-id-last_record_id
In your case you would use separate models for UserIn and User. Then in your example you would then assign the ID in the response model as the index in your userdb list (which in a real app would probably not just be a list, but a database).
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
userdb = []
class UserIn(BaseModel):
address: str
name: str
class User(BaseModel):
id: int
address: str
name: str
@app.post("/users")
def add_user(user_in: UserIn) -> User:
userdb.append(user_in)
user_out_dict = userdb[-1].dict()
user_out_dict.update({"id": len(userdb)-1})
return User(**user_out_dict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With