DEV Community

Ankur Kumar
Ankur Kumar

Posted on Fully Autonomous

Building a FastAPI backend for a Flutter app: auth, errors and the parts tutorials skip

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
Enter fullscreen mode Exit fullscreen mode

Install the dependencies:

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

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

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()),
        },
    )
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Run it:

uvicorn app.main:app --reload
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;

  @override
  String toString() => 'ApiException($statusCode, $code): $message';
}

ApiException toApiException(DioException e) {
  final response = e.response;
  if (response == null) {
    // Timeout, no internet, server not running, TLS failure...
    return ApiException(null, 'network_error', 'Could not reach the server');
  }
  final data = response.data;
  if (data is Map<String, dynamic> && data['code'] is String) {
    return ApiException(
      response.statusCode,
      data['code'] as String,
      (data['message'] ?? '').toString(),
    );
  }
  return ApiException(response.statusCode, 'unknown', 'Something went wrong');
}
Enter fullscreen mode Exit fullscreen mode

A DioException with no response means the request never got an answer: a timeout, no internet, the server is down or a TLS error. Treating that as its own case lets the UI say "Could not reach the server" instead of a confusing status code.

Attach the token and react to 401

An interceptor adds the token to every request, and logs the user out when the API says the token is no longer valid:

// lib/api/api_client.dart
import 'dart:io' show Platform;

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

const _tokenKey = 'access_token';

String get apiBaseUrl {
  if (kIsWeb) return 'http://localhost:8000';
  // The Android emulator reaches your computer's localhost through 10.0.2.2
  if (Platform.isAndroid) return 'http://10.0.2.2:8000';
  return 'http://localhost:8000';
}

class AuthInterceptor extends Interceptor {
  AuthInterceptor(this._storage, this._onUnauthorized);

  final FlutterSecureStorage _storage;
  final VoidCallback _onUnauthorized;

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    final token = await _storage.read(key: _tokenKey);
    if (token != null) {
      options.headers['Authorization'] = 'Bearer $token';
    }
    handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    if (err.response?.statusCode == 401) {
      await _storage.delete(key: _tokenKey);
      _onUnauthorized(); // e.g. navigate to the login screen
    }
    handler.next(err);
  }
}

Dio createDio(FlutterSecureStorage storage, VoidCallback onUnauthorized) {
  return Dio(
    BaseOptions(
      baseUrl: apiBaseUrl,
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 15),
    ),
  )..interceptors.add(AuthInterceptor(storage, onUnauthorized));
}
Enter fullscreen mode Exit fullscreen mode

Notice that the interceptor only reacts to 401. A 403 passes straight through to the screen, which shows the message, because logging out wouldn't fix it.

Log in with form data

// lib/api/auth_repository.dart
import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

import 'api_exception.dart';

class AuthRepository {
  AuthRepository(this._dio, this._storage);

  final Dio _dio;
  final FlutterSecureStorage _storage;

  Future<void> login(String email, String password) async {
    try {
      // OAuth2PasswordRequestForm expects form fields, not JSON
      final response = await _dio.post<Map<String, dynamic>>(
        '/auth/login',
        data: {'username': email, 'password': password},
        options: Options(contentType: Headers.formUrlEncodedContentType),
      );
      await _storage.write(
        key: 'access_token',
        value: response.data!['access_token'] as String,
      );
    } on DioException catch (e) {
      throw toApiException(e);
    }
  }

  Future<void> logout() => _storage.delete(key: 'access_token');
}
Enter fullscreen mode Exit fullscreen mode

Headers.formUrlEncodedContentType is the important line. Send JSON here and FastAPI responds with a 422 validation error.

The model, and a timezone trap

// lib/api/task.dart
class Task {
  Task({
    required this.id,
    required this.title,
    required this.done,
    required this.createdAt,
  });

  final int id;
  final String title;
  final bool done;
  final DateTime createdAt;

  factory Task.fromJson(Map<String, dynamic> json) => Task(
        id: json['id'] as int,
        title: json['title'] as String,
        done: json['done'] as bool,
        createdAt: parseServerTime(json['created_at'] as String),
      );
}

/// SQLite drops the timezone, so the API can send "2026-12-03T09:26:35".
/// Without an offset, Dart would treat that as local time. The server
/// stores UTC, so add the "Z" when it's missing.
DateTime parseServerTime(String value) {
  final hasOffset =
      value.endsWith('Z') || RegExp(r'[+-]\d{2}:\d{2}$').hasMatch(value);
  return DateTime.parse(hasOffset ? value : '${value}Z').toLocal();
}
Enter fullscreen mode Exit fullscreen mode

This one is easy to miss. The API stores created_at in UTC, but SQLite doesn't keep timezone information, so the response contains 2026-12-03T09:26:35.980600 with no offset. Dart's DateTime.parse treats a string without an offset as local time. For a user in India, every timestamp would be 5 hours 30 minutes off. parseServerTime adds the missing Z. PostgreSQL with a timezone-aware column sends the offset, and the function leaves that alone.

The repository

Each method catches DioException and rethrows it as ApiException, so the UI never needs to know about Dio:

// lib/api/task_repository.dart
import 'package:dio/dio.dart';

import 'api_exception.dart';
import 'task.dart';

class TaskRepository {
  TaskRepository(this._dio);

  final Dio _dio;

  Future<List<Task>> fetchTasks() async {
    try {
      final response = await _dio.get<List<dynamic>>('/tasks');
      return response.data!
          .map((json) => Task.fromJson(json as Map<String, dynamic>))
          .toList();
    } on DioException catch (e) {
      throw toApiException(e);
    }
  }

  Future<Task> createTask(String title) async {
    try {
      final response = await _dio.post<Map<String, dynamic>>(
        '/tasks',
        data: {'title': title},
      );
      return Task.fromJson(response.data!);
    } on DioException catch (e) {
      throw toApiException(e);
    }
  }

  Future<void> deleteTask(int id) async {
    try {
      await _dio.delete<void>('/tasks/$id');
    } on DioException catch (e) {
      throw toApiException(e);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Showing loading, errors and data

// lib/tasks_screen.dart
import 'package:flutter/material.dart';

import 'api/api_exception.dart';
import 'api/task.dart';
import 'api/task_repository.dart';

class TasksScreen extends StatefulWidget {
  const TasksScreen({super.key, required this.repository});

  final TaskRepository repository;

  @override
  State<TasksScreen> createState() => _TasksScreenState();
}

class _TasksScreenState extends State<TasksScreen> {
  late Future<List<Task>> _tasks = widget.repository.fetchTasks();

  void _reload() =>
      setState(() => _tasks = widget.repository.fetchTasks());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('My tasks')),
      body: FutureBuilder<List<Task>>(
        future: _tasks,
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            final error = snapshot.error;
            final message = error is ApiException
                ? error.message
                : 'Something went wrong';
            return Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(message),
                  TextButton(onPressed: _reload, child: const Text('Retry')),
                ],
              ),
            );
          }
          final tasks = snapshot.data!;
          if (tasks.isEmpty) {
            return const Center(child: Text('No tasks yet'));
          }
          return ListView.builder(
            itemCount: tasks.length,
            itemBuilder: (context, i) => ListTile(
              title: Text(tasks[i].title),
              trailing: Icon(
                tasks[i].done ? Icons.check_circle : Icons.circle_outlined,
              ),
            ),
          );
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Platform gotchas

The Android emulator can't reach localhost

Inside the emulator, localhost is the emulator itself. Use 10.0.2.2, which the emulator maps to your computer's localhost. That's what apiBaseUrl does.

On a physical phone, neither works. Run the server with uvicorn app.main:app --host 0.0.0.0 and use your computer's local network IP address, with the phone on the same Wi-Fi.

Android blocks plain HTTP

Since Android 9, apps can't make plain http:// requests by default. During development, allow it only in the debug build by adding this to android/app/src/debug/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:usesCleartextTraffic="true" />
</manifest>
Enter fullscreen mode Exit fullscreen mode

Because it lives in the debug folder, release builds still require HTTPS.

Before going to production

  • HTTPS everywhere. Put the API behind a reverse proxy such as Nginx or Caddy, or a platform that provides TLS.
  • A real database. SQLite is fine for one small server. Use PostgreSQL once you have multiple instances or real traffic.
  • Rate limiting on /auth/login to slow down password guessing.
  • CORS only if you need it. Mobile and desktop apps don't use CORS. Add CORSMiddleware only for a web client, and list its exact origin.
  • Tests. FastAPI's TestClient makes it easy to test every error case in the table above.

Conclusion

The parts that make an API pleasant to build against are mostly decided before the first screen: separate input and output schemas, one error format, a clear line between 401 and 403, and a client that turns every failure into one exception type. With those in place, the Flutter side stays small. The interceptor handles tokens, the repository handles errors, and the screen only shows loading, data or a message.

Natural next steps are refresh tokens for longer sessions, and pagination for GET /tasks once lists grow.


Further reading: FastAPI security tutorial, SQLModel, Dio, flutter_secure_storage.

Top comments (0)