Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI - how to generate random ID?

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]
like image 506
cherryBom Avatar asked Oct 20 '25 00:10

cherryBom


2 Answers

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())
like image 165
ti7 Avatar answered Oct 22 '25 16:10

ti7


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)
like image 33
aganders3 Avatar answered Oct 22 '25 16:10

aganders3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!