Most FastAPI tutorials stop at a to-do list with no login, and most Flutter networking tutorials call a public demo API. When you put the two together for a real app, the gaps show up quickly. How should the app store the token? What does it do when the token expires? Why does every error come back in a different shape? And why can't the Android emulator reach localhost?

This tutorial builds a small tasks API with FastAPI and a Flutter client for it. It covers:

  • request and response schemas that never leak internal fields
  • login with JSON Web Tokens (JWT) and Argon2 password hashing
  • one consistent error format, and how the app handles 401 vs 403
  • a Dio client with an auth interceptor and secure token storage
  • the platform quirks: emulator networking, cleartext HTTP and timezones

You'll need Python 3.9+ and Flutter 3.x. The backend code below was tested with FastAPI's TestClient, and the Flutter code with flutter analyze and unit tests.

Project setup

The backend layout:

backend/ app/ __init__.py main.py config.py database.py models.py errors.py auth.py routers/ __init__.py tasks.py .env 

Install the dependencies:

pip install fastapi "uvicorn[standard]" sqlmodel pydantic-settings pyjwt "pwdlib[argon2]" python-multipart 

python-multipart is easy to miss. FastAPI needs it to read the form-encoded login request.

Keep secrets out of the code. pydantic-settings reads them from environment variables or a .env file:

# app/config.py from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env") database_url: str = "sqlite:///./app.db" jwt_secret: str # required: the app won't start without it jwt_algorithm: str = "HS256" access_token_minutes: int = 15 settings = Settings() 

Generate a real secret with python -c "import secrets; print(secrets.token_urlsafe(32))" and put it in .env as JWT_SECRET=.... Add .env to .gitignore.

The database setup uses SQLModel with SQLite, which is enough for development:

# app/database.py from sqlmodel import Session, SQLModel, create_engine from .config import settings engine = create_engine( settings.database_url, connect_args={"check_same_thread": False}, # needed for SQLite only ) def init_db() -> None: SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session 

Models: separate what you store from what you return

A common shortcut is returning database rows directly. That works until you add a field like password_hash and it appears in every response. Define separate schemas for input and output instead:

# app/models.py from datetime import datetime, timezone from typing import Optional from sqlmodel import Field, SQLModel # Database tables class User(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) email: str = Field(unique=True, index=True) password_hash: str class Task(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) title: str done: bool = False owner_id: int = Field(foreign_key="user.id", index=True) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) # What the API accepts and returns class UserCreate(SQLModel): email: str = Field(min_length=3, max_length=254) password: str = Field(min_length=8, max_length=128) class UserRead(SQLModel): id: int email: str class TaskCreate(SQLModel): title: str = Field(min_length=1, max_length=200) class TaskRead(SQLModel): id: int title: str done: bool created_at: datetime 

UserRead has no password_hash, and TaskRead has no owner_id. When a route declares response_model=TaskRead, FastAPI filters the response down to those fields, whatever the database row contains. The Field limits on UserCreate and TaskCreate give you input validation for free.

One error format for the whole API

Before adding routes, decide what errors look like. FastAPI's defaults vary: HTTPException returns {"detail": "..."}, while validation errors return a list of objects. A client then needs special cases for each.

Every error from this API has the same shape:

{"code": "forbidden", "message": "You can only delete your own tasks"} 

code is for the app's logic and never changes. message is for people and can be shown in the UI.

# app/errors.py from fastapi import Request from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException class ApiError(Exception): def __init__(self, status_code: int, code: str, message: str): self.status_code = status_code self.code = code self.message = message async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse: return JSONResponse( status_code=exc.status_code, content={"code": exc.code, "message": exc.message}, ) async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse: # Errors raised by FastAPI itself, e.g. a missing Authorization header or a 404 route return JSONResponse( status_code=exc.status_code, content={"code": "http_error", "message": str(exc.detail)}, headers=getattr(exc, "headers", None), ) async def validation_error_handler(request: Request, exc: RequestValidationError) -> JSONResponse: return JSONResponse( status_code=422, content={ "code": "validation_error", "message": "Some fields are missing or invalid", "details": jsonable_encoder(exc.errors()), }, ) 

The second handler matters more than it looks. When a request has no Authorization header, FastAPI's own security code raises a 401 before your code runs. Without this handler, that one error would come back in the old detail format.

Authentication with JWT

auth.py handles registration, login and the dependency that protects routes:

# app/auth.py from datetime import datetime, timedelta, timezone import jwt from fastapi import APIRouter, Depends from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pwdlib import PasswordHash from sqlmodel import Session, select from .config import settings from .database import get_session from .errors import ApiError from .models import User, UserCreate, UserRead password_hash = PasswordHash.recommended() # Argon2 oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/login") router = APIRouter(prefix="/auth", tags=["auth"]) def create_access_token(user_id: int) -> str: expires = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_minutes) payload = {"sub": str(user_id), "exp": expires} return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm) @router.post("/register", response_model=UserRead, status_code=201) def register(body: UserCreate, session: Session = Depends(get_session)): email = body.email.strip().lower() if session.exec(select(User).where(User.email == email)).first(): raise ApiError(409, "email_taken", "An account with this email already exists") user = User(email=email, password_hash=password_hash.hash(body.password)) session.add(user) session.commit() session.refresh(user) return user @router.post("/login") def login( form: OAuth2PasswordRequestForm = Depends(), session: Session = Depends(get_session), ): email = form.username.strip().lower() user = session.exec(select(User).where(User.email == email)).first() if user is None or not password_hash.verify(form.password, user.password_hash): raise ApiError(401, "invalid_credentials", "Email or password is incorrect") return {"access_token": create_access_token(user.id), "token_type": "bearer"} def get_current_user( token: str = Depends(oauth2_scheme), session: Session = Depends(get_session), ) -> User: try: payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm]) except jwt.ExpiredSignatureError: raise ApiError(401, "token_expired", "Your session has expired. Please log in again") except jwt.InvalidTokenError: raise ApiError(401, "invalid_token", "Invalid access token") user = session.get(User, int(payload["sub"])) if user is None: raise ApiError(401, "invalid_token", "Invalid access token") return user 

A few details worth knowing:

  • Passwords are hashed with Argon2 through pwdlib, which the current FastAPI documentation recommends.
  • Login takes form fields, not JSON. OAuth2PasswordRequestForm follows the OAuth2 spec, so it expects username and password as form data. The field is called username even though it holds an email. This trips up a lot of Flutter clients that send JSON and get a 422 back.
  • The login error doesn't say which part was wrong. "Email or password is incorrect" avoids telling an attacker which emails have accounts.
  • Access tokens are short-lived (15 minutes by default). When one expires, the API returns token_expired, and the app sends the user back to the login screen. For longer sessions, add refresh tokens, which are out of scope here.

The tasks routes

Any route that depends on get_current_user requires a valid token:

# app/routers/tasks.py from typing import List from fastapi import APIRouter, Depends from sqlmodel import Session, select from ..auth import get_current_user from ..database import get_session from ..errors import ApiError from ..models import Task, TaskCreate, TaskRead, User router = APIRouter(prefix="/tasks", tags=["tasks"]) @router.get("", response_model=List[TaskRead]) def list_tasks( user: User = Depends(get_current_user), session: Session = Depends(get_session), ): return session.exec(select(Task).where(Task.owner_id == user.id)).all() @router.post("", response_model=TaskRead, status_code=201) def create_task( body: TaskCreate, user: User = Depends(get_current_user), session: Session = Depends(get_session), ): task = Task(title=body.title, owner_id=user.id) session.add(task) session.commit() session.refresh(task) return task @router.delete("/{task_id}", status_code=204) def delete_task( task_id: int, user: User = Depends(get_current_user), session: Session = Depends(get_session), ): task = session.get(Task, task_id) if task is None: raise ApiError(404, "not_found", "Task not found") if task.owner_id != user.id: raise ApiError(403, "forbidden", "You can only delete your own tasks") session.delete(task) session.commit() 

The delete route shows the difference between the two status codes Flutter apps most often mix up:

  • 401 Unauthorized means "I don't know who you are": no token, a bad token or an expired one. The fix is to log in again.
  • 403 Forbidden means "I know who you are, but you can't do this". Logging in again won't help, so the app should show a message instead.

Some APIs return 404 instead of 403 for other users' items, so they don't reveal that the item exists. Either is reasonable. Just pick one and be consistent.

Wiring it together

# app/main.py from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException from . import auth from .database import init_db from .errors import ( ApiError, api_error_handler, http_error_handler, validation_error_handler, ) from .routers import tasks @asynccontextmanager async def lifespan(app: FastAPI): init_db() yield app = FastAPI(title="Tasks API", lifespan=lifespan) app.add_exception_handler(ApiError, api_error_handler) app.add_exception_handler(StarletteHTTPException, http_error_handler) app.add_exception_handler(RequestValidationError, validation_error_handler) app.include_router(auth.router) app.include_router(tasks.router) 

Run it:

uvicorn app.main:app --reload 

Open http://localhost:8000/docs to see the generated documentation. Use the Authorize button to log in and try the protected routes from the browser.

Here's what the error format looks like in practice. These are real responses from the API above:

Request Status Body
Wrong password 401 {"code": "invalid_credentials", ...}
No token 401 {"code": "http_error", "message": "Not authenticated"}
Expired token 401 {"code": "token_expired", ...}
Delete someone else's task 403 {"code": "forbidden", ...}
Password too short 422 {"code": "validation_error", ...}

The Flutter client

Add the packages:

flutter pub add dio flutter_secure_storage 

Store the token securely

Don't put tokens in SharedPreferences. It's plain storage, readable on rooted devices and from backups. flutter_secure_storage uses the Android Keystore, the iOS Keychain and the Windows Credential Manager.

Turn every failure into one exception type

Mirror the API's error format on the client:

// lib/api/api_exception.dart import 'package:dio/dio.dart'; class ApiException implements Exception { ApiException(this.statusCode, this.code, this.message); final int? statusCode; final String code; final String message; bool get isUnauthorized => statusCode == 401; bool get isForbidden => statusCode == 403; Source:https://dev.to/ankur_kumar_75b0be936c97c/building-a-fastapi-backend-for-a-flutter-app-auth-errors-and-the-parts-tutorials-skip-38n9

Related posts