📚

Comprehensive Notes on Axum Framework for Rust

Jun 4, 2025

Axum Web Framework for Rust - Full Course Notes

Course Overview

  • Sections:
    • Beginner: Hello World, Quick Dev setup, and Static Routing
    • Intermediate: First POST API for login, adding cookies, CRUD operations with a mock model layer
    • Advanced: Custom Middleware, Custom Extractor, Custom Error Handling, and Request Logging
  • Environment Setup:
    • Server terminal on the right
    • Quick Dev client terminal on the left
    • Refresh functionality displays request flow and responses

Beginner Section

Hello World Setup

  • Use tokio::main for async support
  • Add axum to Cargo.toml (ensure latest version)
  • Create first router with path /hello using GET method
  • Return HTML content "Hello World"
  • Setup server with a socket address and bind it

Quick Dev Setup

  • Use cargo test for quick development and testing
  • Add httpc_test as a dev dependency for convenient HTTP client testing
  • Set up watch commands for automatic recompilation on changes

Parameter Handling

  • Add query parameters using Axum extractors
  • Implement a function to handle parameters and default values

Intermediate Section

Login API

  • Set up error handling with custom error module
  • Implement a simple login handler with hardcoded credentials
  • Use cookies for session management
  • Store login tokens in cookies

CRUD Operations

  • Implement a mock model layer for managing Ticket entities
  • Use Arc and Mutex for storing tickets in memory
  • Create, list, and delete tickets with mock data

Advanced Section

Custom Middleware

  • Require authentication middleware to check for cookies
  • Validate and extract user tokens from requests

Context & Extractors

  • Implement custom context extractor to pass user information
  • Share user context across routes and handlers

Error Handling

  • Define server and client error enums for structured error responses
  • Use error mapping to translate server errors into client-friendly formats

Request Logging

  • Implement middleware for request logging
  • Log each request with unique identifiers for tracing

Final Setup

  • Configure main server application with composed routers and middleware
  • Test end-to-end functionality from simple requests to full CRUD and login flows

Key Concepts

  • Axum Features: Routing, middleware, extractors, error handling
  • Rust Features: Async programming with Tokio, error handling via Result, memory safety with ownership and borrowing
  • Development Tools: Cargo for Rust management, HTTP testing tools

Conclusion

  • Axum provides a robust and flexible framework for building web applications in Rust
  • Emphasizes security with careful error handling and request logging
  • Encourages component-based architecture with router composition and middleware layers
  • Supports a full feature set for building scalable and maintainable web applications