Creating Users Table via SQLAlchemy & FastAPI
First we will need to define our Table model in
models.py
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, nullable=False)
email = Column(String, nullable=False, unique=True) # unique prevents email to be registered twice
password = Column(String, nullable=False)
created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))
We should set up a schema for the user registration in the
schemas.py
fileWe can use the
EmailStr
validationThis requires the
email_validator
Module to be installed
Documentation and Additional info: Click here!
The schema should look something like this:
from datetime import datetime
from pydantic import BaseModel, EmailStr
class UserCreate(BaseModel):
email: EmailStr
password: str
Now we will have to create a new path operation in FastAPI's
main.py
file
@app.post("/users", status_code=status.HTTP_201_CREATED)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db), ):
new_user = models.User(**user.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
Once we test this via postman we should get the response like this:
{
"created_at": "2022-07-29T10:00:43.106836+03:00",
"email": "[email protected]",
"password": "Password123",
"id": 3
}
These is an issue with this, we should never send the PASSWORD back to the user
We need to define a user response in
schemas.py
class UserOut(BaseModel):
id: int
email: EmailStr
created_at: datetime
class Config:
orm_mode = True
We also need to update our response model in
main.py
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db), ):
new_user = models.User(**user.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
We should get a proper response now with EMAIL and ID:
{
"id": 6,
"email": "[email protected]",
"created_at": "2022-07-29T10:06:31.160227+03:00"
}
YOU SHOULD NEVER STORE THE PASSWORDS IN CLEAR TEXT AS IN THIS EXAMPLE
Click here to see how to HASH Passwords
Last updated