python
52 lines · 8 steps
Building a signup endpoint in FastAPI
A user-registration route that validates input, checks for duplicates, persists to the database, and sends a welcome email in the background.
Explained by
highlit
1from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
2from pydantic import BaseModel, EmailStr
3from sqlalchemy.orm import Session
4
5from .database import get_db
6from .models import User
7from .services.mailer import send_email
8
9router = APIRouter(prefix="/users", tags=["users"])
10
11
12class SignupRequest(BaseModel):
13 email: EmailStr
14 full_name: str
15
16
17class SignupResponse(BaseModel):
18 id: int
19 email: EmailStr
20
21 class Config:
22 from_attributes = True
23
24
25def send_welcome_email(email: str, full_name: str) -> None:
26 send_email(
27 to=email,
28 subject="Welcome aboard!",
29 template="welcome",
30 context={"name": full_name},
31 )
32
33
34@router.post("", response_model=SignupResponse, status_code=status.HTTP_201_CREATED)
35def signup(
36 payload: SignupRequest,
37 background_tasks: BackgroundTasks,
38 db: Session = Depends(get_db),
39) -> User:
40 if db.query(User).filter(User.email == payload.email).first():
41 raise HTTPException(
42 status_code=status.HTTP_409_CONFLICT,
43 detail="A user with this email already exists.",
44 )
45
46 user = User(email=payload.email, full_name=payload.full_name)
47 db.add(user)
48 db.commit()
49 db.refresh(user)
50
51 background_tasks.add_task(send_welcome_email, user.email, user.full_name)
52 return user
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Pydantic models validate incoming JSON and shape outgoing responses, keeping the endpoint body free of manual parsing.
- 2Depends lets FastAPI inject a per-request database session so the handler never manages its own connection lifecycle.
- 3BackgroundTasks defers slow work like email until after the response is sent, keeping the request fast.
Related explainers
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
python
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent
How a Django settings module is wired
configuration
environment-variables
middleware
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-signup-endpoint-in-fastapi-explained-python-f7e8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.