Skip to content

LucaPaterlini/axum-rest-api

Repository files navigation

Axum REST API Example with Swagger

A complete REST API built with Axum, SQLx, PostgreSQL, and Swagger UI documentation.

Features

  • ✅ Full CRUD operations
  • ✅ PostgreSQL database with SQLx
  • ✅ Automatic database migrations
  • ✅ Request logging and tracing
  • ✅ CORS support
  • Interactive Swagger UI documentation
  • ✅ OpenAPI 3.0 specification

Prerequisites

  • Rust (latest stable)
  • PostgreSQL database

Setup

  1. Clone the repository

  2. Copy .env.example to .env and update the database URL:

    cp .env.example .env
  3. Create a PostgreSQL database:

    CREATE DATABASE mydb;
  4. Run the application (migrations run automatically):

    cargo run
  5. Open Swagger UI at: http://localhost:3000/swagger-ui

API Documentation

Swagger UI

Visit http://localhost:3000/swagger-ui for interactive API documentation where you can:

  • View all available endpoints
  • See request/response schemas
  • Test API calls directly from the browser
  • Download the OpenAPI specification

OpenAPI JSON

Access the raw OpenAPI spec at: http://localhost:3000/api-docs/openapi.json

API Endpoints

  • GET /users - List all users
  • POST /users - Create a new user
  • GET /users/:id - Get user by ID
  • PUT /users/:id - Update user
  • DELETE /users/:id - Delete user

Example Requests

Create User

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "john@example.com"}'

Get All Users

curl http://localhost:3000/users

Get User by ID

curl http://localhost:3000/users/1

Update User

curl -X PUT http://localhost:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Jane Doe"}'

Delete User

curl -X DELETE http://localhost:3000/users/1

Project Structure

src/
├── main.rs       # Application entry point with OpenAPI setup
├── models.rs     # Data models with schema annotations
├── db.rs         # Database operations
├── handlers.rs   # HTTP handlers with OpenAPI documentation
└── routes.rs     # Route definitions

migrations/
└── 20240101000000_create_users.sql

Dependencies

  • axum - Web framework
  • tokio - Async runtime
  • sqlx - Async PostgreSQL driver
  • tower-http - HTTP middleware (CORS, tracing)
  • utoipa - OpenAPI documentation generation
  • utoipa-swagger-ui - Swagger UI integration

Development

The Swagger UI automatically updates when you modify the API endpoints. Just restart the server to see your changes reflected in the documentation!

Docker Deployment

Using Docker Compose (Recommended)

The easiest way to run the entire stack:

# Build and start both PostgreSQL and the API
docker-compose up --build

# Run in detached mode
docker-compose up -d --build

# View logs
docker-compose logs -f

# Stop services
docker-compose down

# Stop and remove volumes
docker-compose down -v

The API will be available at:

Manual Docker Build

If you want to build just the API container:

# Build the image
docker build -t axum-api .

# Run with external PostgreSQL
docker run -p 3000:3000 \
  -e DATABASE_URL=postgres://user:pass@host:5432/db \
  axum-api

Docker Architecture

The Dockerfile uses a two-stage build:

  1. Builder Stage (rust:1.75-slim)

    • Installs build dependencies
    • Compiles the Rust application in release mode
    • Produces optimized binary
  2. Runtime Stage (scratch)

    • Minimal image with no OS
    • Only contains the compiled binary and SSL certificates
    • Extremely small image size (~10-15MB)
    • Enhanced security with minimal attack surface

PostgreSQL Container

The docker-compose.yml sets up:

  • PostgreSQL 16 Alpine (lightweight)
  • Health checks to ensure database is ready
  • Persistent volume for data
  • Automatic network configuration
  • Environment variables for easy configuration

Production Considerations

For production deployments:

  1. Change default passwords in docker-compose.yml
  2. Use secrets management instead of environment variables
  3. Add resource limits:
    deploy:
      resources:
        limits:
          cpus: '0.5'
          memory: 512M
  4. Use a reverse proxy (nginx, traefik) for SSL/TLS
  5. Enable database backups
  6. Consider using a managed PostgreSQL service

About

sample of rust api

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published