User Registration and Management
To create and manage user accounts during local development without authentication or superuser checks, use the private API routes and the PrivateUserCreate schema.
Creating a User via Private Routes
You can create a new user by sending a POST request to the /private/users/ endpoint. This is typically used for seeding initial data or setting up test accounts.
import httpx
def create_dev_user():
response = httpx.post(
"http://localhost:8000/api/v1/private/users/",
json={
"email": "dev@example.com",
"password": "securepassword123",
"full_name": "Development User",
"is_verified": True
}
)
return response.json()
The Private User Schema
The PrivateUserCreate class in backend/app/api/routes/private.py defines the structure for these requests. Unlike the standard UserCreate schema, it uses basic string types and allows setting the verification status directly.
class PrivateUserCreate(BaseModel):
email: str
password: str
full_name: str
is_verified: bool = False
Enabling Private Routes
Private routes are conditionally included in the application based on the environment configuration. They are only available when the ENVIRONMENT variable is set to local.
In backend/app/api/main.py:
if settings.ENVIRONMENT == "local":
api_router.include_router(private.router)
Implementation Details
The create_user function in backend/app/api/routes/private.py handles the creation logic. It hashes the provided password using get_password_hash and saves the user directly to the database using the SessionDep dependency.
@router.post("/users/", response_model=UserPublic)
def create_user(user_in: PrivateUserCreate, session: SessionDep) -> Any:
"""
Create a new user.
"""
user = User(
email=user_in.email,
full_name=user_in.full_name,
hashed_password=get_password_hash(user_in.password),
)
session.add(user)
session.commit()
return user
Troubleshooting and Limitations
- Duplicate Emails: The private creation endpoint does not check if a user with the same email already exists. Since the
Usermodel inbackend/app/models.pyenforces a unique constraint on theemailfield, attempting to create a duplicate user will result in a database integrity error. - Email Validation:
PrivateUserCreateuses thestrtype for the email field instead ofEmailStr. This means the API will not automatically validate the format of the email address during the request. - Environment Restriction: If you receive a 404 error when accessing
/api/v1/private/users/, ensure that yourENVIRONMENTvariable is explicitly set tolocalin your.envfile or environment settings.