<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Quentin Piot on Medium]]></title>
        <description><![CDATA[Stories by Quentin Piot on Medium]]></description>
        <link>https://medium.com/@qkpiot?source=rss-8d681083b2ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ci8UegR_6wP2rIvvvx__0w.jpeg</url>
            <title>Stories by Quentin Piot on Medium</title>
            <link>https://medium.com/@qkpiot?source=rss-8d681083b2ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:19:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@qkpiot/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[2026 UPDATE] Building a Clean Rust Backend with Axum, Diesel, PostgreSQL and DDD: From Concept to…]]></title>
            <link>https://medium.com/@qkpiot/building-a-robust-rust-backend-with-axum-diesel-postgresql-and-ddd-from-concept-to-deployment-b25cf5c65bc8?source=rss-8d681083b2ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/b25cf5c65bc8</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[Quentin Piot]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 14:22:54 GMT</pubDate>
            <atom:updated>2026-01-23T14:46:33.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>[2026 UPDATE] Building a Clean Rust Backend with Axum, Diesel, PostgreSQL and DDD: From Concept to Deployment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qUujTd1UzjAj8oIU" /><figcaption>Photo by <a href="https://unsplash.com/@blender_person?utm_source=medium&amp;utm_medium=referral">Wesley Ford</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>2026 UPDATE</strong></h3><blockquote><em>Returning to a personal project after a long hiatus often means spending the first few hours negotiating with the compiler. This commit represents exactly that necessary friction: aligning the codebase with the standards of 2026. The most significant shift here is undoubtedly the migration to the </em><strong><em>Rust 2024 Edition</em></strong><em>. This wasn’t just about tweaking a line in </em><em>Cargo.toml; it was an opportunity to delete a massive amount of boilerplate. Thanks to the full stabilization of </em><em>async fn in traits and the refined lifetime elision rules, I was finally able to strip out the </em><em>#[async_trait] macros that were cluttering up my services. The code breathes better now, and function signatures finally reflect business intent rather than borrower constraints.</em></blockquote><blockquote><em>On the web side, the </em><strong><em>Axum</em></strong><em> update required a bit of gymnastics. The latest versions have further refined the extractor system and shared </em><em>State management. I took this opportunity to refactor how I inject connection pools: it’s more explicit, strictly type-safe, and allowed me to fix a couple of handlers that were dragging around implicit dependencies. It’s the kind of invisible technical debt that accumulates strictly because we don&#39;t force these version bumps often enough.</em></blockquote><blockquote><em>To lock these changes in, I also tightened the screws on the tooling. I updated the </em><strong><em>Rustfmt</em></strong><em> and </em><strong><em>Clippy</em></strong><em> configurations to match the stricter 2026 defaults.</em></blockquote><blockquote><em>Finally, I couldn’t leave the infrastructure rotting in the past. I overhauled the </em><strong><em>Dockerfile</em></strong><em>, bumping the builder images to support the new toolchain and optimizing the multi-stage build to keep the final artifact slim.</em></blockquote><h3>2025 UPDATE</h3><blockquote><em>Major Dependency Upgrade: Moving to Axum 0.8+, Diesel 2.x, and Tokio 1.x</em></blockquote><blockquote><em>I recently undertook a significant upgrade of the core dependencies for my “axum-diesel-real-world” project. The goal was to move to the latest versions of Axum (likely 0.8+), Diesel (2.x), and Tokio (1.x), while ensuring everything compiles with a recent Rust version. This kind of update is crucial for leveraging the latest features, performance improvements, and security patches, but it often comes with its share of breaking changes.<br>Here’s a summary of the modifications and challenges encountered:</em></blockquote><blockquote><em>Updating Dependencies in Cargo.toml:</em></blockquote><blockquote><em>Axum, Tokio, Diesel, diesel_migrations, deadpool-diesel, tracing, and tracing-subscriber were updated to their latest stable versions.</em></blockquote><blockquote><em>Adapting to Axum API Changes (0.8+):</em></blockquote><blockquote><em>Application Serving: axum::serve(listener, app) is now the standard way to start the server, replacing older approaches like into_make_service_with_connect_info.<br>Route Parameter Syntax: The syntax for capturing path segments changed from /:param to /{param}. All route definitions using captures (e.g., /posts/:id became /posts/{id}) had to be updated.<br>State Management (AppState): I ensured AppState was correctly cloned and passed to nested routers and the main application via .with_state(), resolving ownership issues.</em></blockquote><blockquote><em>Adjustments for Diesel and diesel_migrations:</em></blockquote><blockquote><em>MigrationHarness: To run migrations at startup (conn.run_pending_migrations(MIGRATIONS)), it’s now necessary to import the diesel_migrations::MigrationHarness trait.<br>Imports: The embed_migrations and EmbeddedMigrations types were correctly imported.<br>Module Structure: The schema.rs (generated by Diesel CLI) and models.rs (for my data structure definitions) modules were confirmed and correctly declared.</em></blockquote><blockquote><em>Connection Pool Management (deadpool-diesel):</em></blockquote><blockquote><em>Imports for Pool and Manager from deadpool-diesel (specifically for Postgres) were verified and corrected.</em></blockquote><blockquote><em>Tracing Configuration (tracing-subscriber):</em></blockquote><blockquote><em>To use methods like .with() on tracing_subscriber::registry(), importing the SubscriberExt trait (often via tracing_subscriber::prelude::*) became necessary.</em></blockquote><blockquote><em>Module Organization and Miscellaneous Error Resolution:</em></blockquote><blockquote><em>Several modules (errors, handlers, routes, state, config) were declared. I had to ensure the corresponding files (src/module_name.rs or src/module_name/mod.rs) existed.<br>Duplicate module declarations were removed.<br>Various import errors and visibility issues (private fields in request structs) were fixed.<br>dead_code warnings in errors.rs were noted, indicating future work to fully integrate error handling or clean up the code.</em></blockquote><p>In the ever-evolving landscape of web development, Rust has emerged as a compelling choice for building robust and high-performance backend systems. Leveraging Rust’s memory safety guarantees and expressive type system, this article takes you on a journey to create a real-world backend application using cutting-edge technologies like <strong>Axum</strong>, <strong>Diesel</strong>, and <strong>Domain-Driven Design</strong> (DDD).</p><p>But we’re not stopping there! We’ll also explore how to supercharge your application with <strong>Redis</strong>, using it as both a cache and a locking mechanism, to optimize performance and enhance scalability.</p><p>Along the way, we’ll delve into the fundamentals of structuring a modular, maintainable codebase and guide you through the process of containerizing your application with <strong>Docker</strong> for easy deployment. Additionally, to fortify your application’s security, we’ll explore the intricacies of adding OAuth authentication.</p><p>So, fasten your seatbelts, as we embark on a comprehensive exploration of modern Rust backend development, from inception to deployment and beyond. <strong>Let’s get started!</strong></p><p><strong>Link to the GitHub Repository : </strong><a href="https://github.com/Quentin-Piot/axum-diesel-real-world"><strong>https://github.com/Quentin-Piot/axum-diesel-real-world</strong></a></p><p>Link to my LinkedIn Profile : <a href="https://www.linkedin.com/in/quentin-piot/">https://www.linkedin.com/in/quentin-piot/</a></p><blockquote>The primary aim of this blog post is not to provide an in-depth tutorial on Rust programming language or the intricacies of querying databases with Diesel ORM. While we’ll touch on essential Rust and Diesel concepts, the primary goal is to illustrate the end-to-end development process and best practices for building a robust backend solution.</blockquote><h3>Part 1 : Initializing the Codebase</h3><p>To kickstart our journey, you’ll need to have Rust installed on your machine. If you haven’t already, you can install Rust by following the instructions on <a href="https://www.rust-lang.org/">the official website</a>. Once Rust is up and running, we can create our project.</p><p>Open your terminal and use the following command to create a new Rust project:</p><pre>cargo new axum-diesel-real-world</pre><p>This command will generate a new directory called axum-diesel-real-world with the basic structure for a Rust project.</p><h4>Adopting a Modular Structure</h4><p>To effectively apply Domain-Driven Design (DDD) principles, we’ll structure our project in a modular fashion, mirroring the key domains and capabilities of our application. Here’s the hierarchy we’ll be following:</p><pre>axum-diesel-real-world/<br>  ├── src/<br>  │   ├── domain/<br>  │   │   ├── models/<br>  │   │   ├── mod.rs<br>  │   ├── handlers/<br>  │   ├── infra/<br>  │   │   ├── db/<br>  │   │   ├── repositories/<br>  │   ├── utils/<br>  │   │   ├── custom_extractors/<br>  │   ├── main.rs<br>  │   ├── routes.rs<br>  │   ├── config.rs<br>  │   ├── state.rs<br>  │   ├── error.rs<br>  ├── migrations/<br>  ├── Cargo.toml<br>  └── README.md</pre><p>In this structure:</p><ul><li>domain/ houses your domain logic following DDD principles, with a subdirectory models/ for defining your domain models.</li><li>handlers/ is where you define your API handlers.</li><li>infra/ encompasses your infrastructure logic, further divided into db/ for database-related logic and repositories/ for defining repositories.</li><li>utils/ is where you define utility functions, including custom extractors for Axum.</li></ul><p>This modular approach not only adheres to DDD principles but also ensures that your codebase remains organized and maintainable as your project grows.</p><h4>Setting Up Initial Dependencies</h4><p>As our project evolves, we’ll rely on external libraries and frameworks to streamline development. Let’s begin by setting up the initial dependencies in our Cargo.toml file:</p><pre>[dependencies]<br>axum = { version = &quot;0.8&quot;, features = [&quot;macros&quot;, &quot;tokio&quot;] }<br>axum-macros = &quot;0.5&quot;<br>chrono = { version = &quot;0.4.41&quot;, features = [&quot;serde&quot;] }<br>diesel = { version = &quot;2.2&quot;, features = [&quot;postgres&quot;, &quot;uuid&quot;, &quot;serde_json&quot;] }<br>diesel_migrations = &quot;2&quot;<br>deadpool-diesel = { version = &quot;0.6&quot;, features = [&quot;postgres&quot;] }<br>dotenvy = &quot;0.15&quot;<br>serde = { version = &quot;1.0&quot;, features = [&quot;derive&quot;] }<br>serde_json = &quot;1.0&quot;<br>tokio = { version = &quot;1.45&quot;, features = [&quot;sync&quot;, &quot;macros&quot;, &quot;rt-multi-thread&quot;] }<br>tracing = &quot;0.1&quot;<br>tracing-subscriber = { version = &quot;0.3&quot;, features = [&quot;env-filter&quot;] }<br>uuid = { version = &quot;1.17&quot;, features = [&quot;fast-rng&quot;, &quot;v4&quot;, &quot;serde&quot;] }</pre><h4>Configure PostgreSQL database and environment file</h4><p>To install PostgreSQL on your machine, please follow the official installation instructions provided in the <a href="https://www.postgresql.org/download/">PostgreSQL documentation</a>.</p><p>Create next a database and then save the database url in an .env file. You’ll also need to specify the port and the host you need your server to start on.</p><p>For information, <strong>127.0.0.1 </strong>is the default port corresponding to localhost while we’ll need to use <strong>0.0.0.0</strong> if it is running in a Docker container</p><pre>DATABASE_URL=postgres://postgres:postgres@localhost/&lt;DATABASE_NAME&gt;<br>PORT=3000<br>HOST=127.0.0.1</pre><h4>Creating the server in your main.rs file</h4><p>In your main.rs file, you&#39;ll define the entry point for your Rust backend application. This is where you&#39;ll set up and configure the server using the Axum framework. Axum provides a powerful and ergonomic way to build asynchronous web applications. You&#39;ll define your application&#39;s routes, middleware, and server configuration in this file, allowing your backend to listen for incoming HTTP requests and respond accordingly. We&#39;ll explore this in more detail as we progress through the development of our Rust backend solution.</p><p>The code will be explained below, you can also find some comments on it:</p><p><strong>src/main.rs</strong></p><pre>use deadpool_diesel::postgres::{Manager, Pool};<br>use deadpool_diesel::Runtime;<br>use diesel_migrations::{embed_migrations, EmbeddedMigrations};<br>use std::net::SocketAddr;<br>use tracing_subscriber::prelude::*;<br>use diesel_migrations::MigrationHarness;<br><br>// Define modules for different parts of the application<br>mod config;<br>mod domain;<br>mod errors;<br>mod handlers;<br>mod infra;<br>mod routes;<br>mod state;<br>mod utils;<br><br>// Import necessary items from modules<br>use crate::config::config;<br>use crate::errors::{internal_error, AppError};<br>use crate::routes::app_router;<br>use crate::state::AppState;<br><br>// Embed database migrations<br>pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!(&quot;migrations/&quot;);<br><br>// Main asynchronous function to start the application<br>#[tokio::main]<br>async fn main() {<br>    // Initialize tracing for logging<br>    init_tracing();<br><br>    // Load application configuration<br>    let app_config = config().await;<br><br>    // Create a connection manager for the database pool<br>    let manager = Manager::new(app_config.db_url().to_string(), Runtime::Tokio1);<br>    // Build the connection pool<br>    let pool = Pool::builder(manager)<br>        .build()<br>        .expect(&quot;Failed to create connection pool&quot;);<br><br>    // Run database migrations<br>    if let Err(err) = run_migrations(&amp;pool).await {<br>        tracing::error!(&quot;Failed to run migrations: {:?}&quot;, err);<br>        // Consider exiting the application or handling the error appropriately<br>        return;<br>    }<br><br>    // Create application state containing the connection pool<br>    let state = AppState { pool };<br><br>    // Create the application router with the defined routes<br>    let app = app_router(state.clone());<br><br>    // Get server host and port from configuration<br>    let host = app_config.server_host();<br>    let port = app_config.server_port();<br>    let address = format!(&quot;{}:{}&quot;, host, port);<br>    // Parse the address into a SocketAddr<br>    let socket_addr: SocketAddr = address.parse().expect(&quot;Unable to parse socket address&quot;);<br><br>    // Log the server address<br>    tracing::info!(&quot;listening on http://{}&quot;, socket_addr);<br><br>    // Bind the server to the specified address<br>    let listener = tokio::net::TcpListener::bind(socket_addr)<br>        .await<br>        .expect(&quot;Failed to bind&quot;);<br><br>    // Start the axum server<br>    axum::serve(listener, app)<br>        .await<br>        .expect(&quot;Server failed to run&quot;);<br>}<br><br>// Function to initialize tracing<br>fn init_tracing() {<br>    tracing_subscriber::registry()<br>        .with(<br>            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {<br>                &quot;example_tokio_postgres=debug,axum_diesel_real_world=debug&quot;.into()<br>            }),<br>        )<br>        .with(tracing_subscriber::fmt::layer())<br>        .init();<br>}<br><br>// Asynchronous function to run database migrations<br>async fn run_migrations(pool: &amp;Pool) -&gt; Result&lt;(), AppError&gt; {<br>    // Get a database connection from the pool<br>    let conn = pool.get().await.map_err(internal_error)?;<br>    // Run pending migrations on the connection<br>    conn.interact(|conn_inner| conn_inner.run_pending_migrations(MIGRATIONS).map(|_| ()))<br>        .await<br>        .map_err(internal_error)? // Handle potential errors from the interact block<br>        .map_err(internal_error)?; // Handle potential errors from run_pending_migrations<br>    Ok(())<br>}</pre><p><em>So what is happening here ?</em></p><p>In this code, we are setting up the entry point for our Rust backend application. The main function, marked with #[tokio::main], serves as the starting point of our server. Here&#39;s a breakdown of the key actions:</p><ol><li>We initialize the logging and tracing infrastructure to capture application events and provide valuable debugging information.</li><li>Configuration settings are loaded from the environment, including the database connection details and server settings.</li><li>A connection pool to the PostgreSQL database is created using the deadpool-diesel and diesel libraries, allowing efficient and asynchronous database access.</li><li>Pending database migrations are applied to ensure that the database schema is up-to-date with our codebase. We utilize the diesel-migrations crate to manage these migrations.</li><li>An instance of the application state is created to hold the database connection pool, making it accessible to various parts of our application using dependency injection.</li><li>We configure our application’s routes, middleware, and server settings using the Axum framework.</li><li>The server is configured to listen on a specified host and port, and the server’s listening address is logged for reference.</li><li>Finally, the Axum server is started, serving the configured application and handling incoming HTTP requests.</li></ol><h4>Global configuration</h4><p>With Tokio, it is simple to have a global configuration file using OnceCell, a crate that allows you to initialize and store a value once, and then access that value efficiently across your application.</p><p>Let’s create a config.rs file at root level that will generate a OnceCell containing the configuration file with data loaded from environment file :</p><p><strong>src/config.rs</strong></p><pre>// Import necessary modules<br>use std::env;<br>use dotenvy::dotenv;<br>use tokio::sync::OnceCell;<br><br>// Define a struct to represent server configuration<br>#[derive(Debug)]<br>struct ServerConfig {<br>    host: String,<br>    port: u16,<br>}<br><br>// Define a struct to represent database configuration<br>#[derive(Debug)]<br>struct DatabaseConfig {<br>    url: String,<br>}<br><br>// Define a struct that aggregates server and database configuration<br>#[derive(Debug)]<br>pub struct Config {<br>    server: ServerConfig,<br>    db: DatabaseConfig,<br>}<br><br>// Implement methods for the Config struct to access configuration values<br>impl Config {<br>    // Getter method for the database URL<br>    pub fn db_url(https://medium.com/&amp;self) -&gt; &amp;str {<br>        &amp;self.db.url<br>    }<br><br>    // Getter method for the server host<br>    pub fn server_host(&amp;self) -&gt; &amp;str {<br>        &amp;self.server.host<br>    }<br><br>    // Getter method for the server port<br>    pub fn server_port(&amp;self) -&gt; u16 {<br>        self.server.port<br>    }<br>}<br><br>// Create a static OnceCell to store the application configuration<br>pub static CONFIG: OnceCell&lt;Config&gt; = OnceCell::const_new();<br><br>// Asynchronously initialize the configuration<br>async fn init_config() -&gt; Config {<br>    // Load environment variables from a .env file if present<br>    dotenv().ok();<br><br>    // Create a ServerConfig instance with default values or values from environment variables<br>    let server_config = ServerConfig {<br>        host: env::var(&quot;HOST&quot;).unwrap_or_else(|_| String::from(&quot;127.0.0.1&quot;)),<br>        port: env::var(&quot;PORT&quot;)<br>            .unwrap_or_else(|_| String::from(&quot;3000&quot;))<br>            .parse::&lt;u16&gt;()<br>            .unwrap(),<br>    };<br><br>    // Create a DatabaseConfig instance with a required DATABASE_URL environment variable<br>    let database_config = DatabaseConfig {<br>        url: env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set&quot;),<br>    };<br><br>    // Create a Config instance by combining server and database configurations<br>    Config {<br>        server: server_config,<br>        db: database_config,<br>    }<br>}<br><br>// Asynchronously retrieve the application configuration, initializing it if necessary<br>pub async fn config() -&gt; &amp;&#39;static Config {<br>    // Get the configuration from the OnceCell or initialize it if it hasn&#39;t been set yet<br>    CONFIG.get_or_init(init_config).await<br>}</pre><p>This code defines a configuration structure that aggregates server and database configuration settings. It uses the dotenvy crate to load environment variables from a .env file and sets default values for server configuration. The OnceCell ensures that the configuration is initialized only once and can be accessed globally throughout the application. The config function allows other parts of the application to asynchronously retrieve the configuration, initializing it if necessary.</p><h4>Write router</h4><p>In order to have a cleaner code, I decided to put the router in a separate file router.rs that will handle for now only GET call to the route of the api, but also have a fallback returning a 404 response</p><p><strong>src/router.rs</strong></p><pre>use axum::{<br>    http::StatusCode,<br>    response::IntoResponse,<br>    routing::{get, post},<br>    Router,<br>};<br><br>// Import handlers for post-related operations<br>use crate::handlers::posts::{create_post, get_post, list_posts};<br>// Import the application state<br>use crate::AppState;<br><br>// Function to create the main application router<br>pub fn app_router(state: AppState) -&gt; Router {<br>    Router::new()<br>        // Define the root route<br>        .route(&quot;/&quot;, get(root))<br>        // Define a fallback handler for 404 errors<br>        .fallback(handler_404)<br>        // Attach the application state to the router<br>        .with_state(state)<br>}<br><br>// Handler for the root route<br>async fn root() -&gt; &amp;&#39;static str {<br>    &quot;Server is running!&quot;<br>}<br><br>// Handler for 404 Not Found errors<br>async fn handler_404() -&gt; impl IntoResponse {<br>    (<br>        StatusCode::NOT_FOUND,<br>        &quot;The requested resource was not found&quot;,<br>    )<br>}</pre><p>Now we have our codebase, let’s work on our first context : Posts !</p><h3>Part 2: Create our first context : Posts</h3><h4>Setup diesel and migrations</h4><p>In order to make the usage of Diesel easier, you can install the CLI tool using Cargo:</p><pre>cargo install diesel_cli --no-default-features --features &quot;postgres&quot;</pre><p>Then you need to specify your Database Url in your .env file :</p><pre>DATABASE_URL=postgres://postgres:postgres@localhost/&lt;DATABASE_NAME&gt;</pre><p>We now just have to setup everything using the following command tool :</p><pre>diesel setup</pre><p>It will create your database, generate a diesel.toml file at root level and generate a migration folder with an example</p><p>Let’s write our first migration. We can use the command line tool to generate it automatically:</p><pre>diesel migration generate create_posts</pre><p>We can now create our first object : Posts working with both up.sql and down.sql files</p><p>I have decided to use UUID to reduce the chances of collisions or conflicts, even when data is distributed across different databases or instances.</p><p><strong>up.sql</strong></p><pre>CREATE TABLE posts<br>(<br>    id        uuid PRIMARY KEY DEFAULT uuid_generate_v4(),<br>    title     VARCHAR NOT NULL,<br>    body      TEXT    NOT NULL,<br>    published BOOLEAN NOT NULL DEFAULT FALSE<br>)</pre><p><strong>down.sql</strong></p><pre>DROP TABLE posts</pre><p>Now our migration is ready, we can run it through the CLI tool in order to generate a schema. But first, let’s change the default schema destination to work with our data structure :</p><p><strong>diesel.rs</strong></p><pre><br>[print_schema]<br>file = &quot;src/infra/db/schema.rs&quot;<br>custom_type_derives = [&quot;diesel::query_builder::QueryId&quot;]<br><br>[migrations_directory]<br>dir = &quot;migrations&quot;</pre><p>We can now apply our migration :</p><pre>diesel migration run</pre><p>A new file has been created in our src/infra/db folder :</p><p><strong>schema.sql</strong></p><pre>diesel::table! {<br>    posts (id) {<br>        id -&gt; Uuid,<br>        title -&gt; Varchar,<br>        body -&gt; Text,<br>        published -&gt; Bool,<br>    }<br>}</pre><p>This table! macro will create a new public module, with the same name, as the name of the table. In this module, you will find a unit struct named table, and a unit struct with the name of each column. It will be used to interact with the database later on</p><p>Well done, we now have everything ready to finally start coding !</p><h4>Create our post model</h4><p>Let’s move to our domain and create our post model.</p><p><strong>src/domain/post.rs</strong></p><pre>#[derive(Clone, Debug, PartialEq)]<br>pub struct PostModel {<br>    pub id: Uuid,<br>    pub title: String,<br>    pub body: String,<br>    pub published: bool,<br>}</pre><p>We can also add Errors linked to this domain to make error handling much reliable and easy to understand.</p><pre>#[derive(Debug)]<br>pub enum PostError {<br>    InternalServerError,<br>    NotFound(Uuid),<br>    InfraError(InfraError),<br>}</pre><p>In Axum, every type returned by a handler must implements <strong>IntoResponse. </strong>Let’s do it for our new PostError enum</p><pre>impl IntoResponse for PostError {<br>    fn into_response(self) -&gt; axum::response::Response {<br>        let (status, err_msg) = match self {<br>            Self::NotFound(id) =&gt; (<br>                StatusCode::NOT_FOUND,<br>                format!(&quot;PostModel with id {} has not been found&quot;, id),<br>            ),<br>            Self::InfraError(db_error) =&gt; (<br>                StatusCode::INTERNAL_SERVER_ERROR,<br>                format!(&quot;Internal server error: {}&quot;, db_error),<br>            ),<br>            _ =&gt; (<br>                StatusCode::INTERNAL_SERVER_ERROR,<br>                String::from(&quot;Internal server error&quot;),<br>            ),<br>        };<br>        (<br>            status,<br>            Json(<br>                json!({&quot;resource&quot;:&quot;PostModel&quot;, &quot;message&quot;: err_msg, &quot;happened_at&quot; : chrono::Utc::now() }),<br>            ),<br>        )<br>            .into_response()<br>    }<br>}</pre><p>As it’s a very simple usecase, it’s all we need in our model for now. Let’s move to our repository and implement the basic CRUD operations. We will see how to interact with our database and return our model</p><h4>Global errors handling</h4><p>Let’s create a file at root levelerror.rs to handle global level errors. It will help later on in your appliaction</p><p><strong>src/errors.rs</strong></p><pre>// Import necessary modules and types<br>use axum::http::StatusCode;<br>use axum::Json;<br>use axum::response::IntoResponse;<br>use serde_json::json;<br><br>// Define an enumeration for custom application errors<br>#[derive(Debug)]<br>pub enum AppError {<br>    InternalServerError,        // Represents an internal server error<br>    BodyParsingError(String),   // Represents an error related to request body parsing<br>}<br><br>// Define a util to create an internal server error<br>pub fn internal_error&lt;E&gt;(_err: E) -&gt; AppError {<br>    AppError::InternalServerError<br>}<br><br>// Implement the `IntoResponse` trait for the `AppError` enumeration<br>impl IntoResponse for AppError {<br>    // Define the conversion to an Axum response<br>    fn into_response(self) -&gt; axum::response::Response {<br>        // Define status and error message based on the error variant<br>        let (status, err_msg) = match self {<br>            Self::InternalServerError =&gt; (<br>                StatusCode::INTERNAL_SERVER_ERROR,<br>                String::from(&quot;Internal Server Error&quot;),<br>            ),<br>            Self::BodyParsingError(message) =&gt; (<br>                StatusCode::BAD_REQUEST,<br>                format!(&quot;Bad request error: {}&quot;, message),<br>            ),<br>        };<br>        <br>        // Create a JSON response containing the error message<br>        (status, Json(json!({ &quot;message&quot;: err_msg }))).into_response()<br>    }<br>}</pre><ul><li>The code defines an AppError enumeration with two variants:</li><li>InternalServerError: Represents an internal server error.</li><li>BodyParsingError: Represents an error related to request body parsing and includes a custom error message.</li><li>The internal_error function is defined to create instances of the InternalServerError variant.</li><li>The IntoResponse trait is implemented for the AppError enumeration, allowing instances of AppError to be converted into Axum responses.</li><li>Inside the into_response method implementation, the code matches the error variant to determine the HTTP status code and error message to be returned in the response.</li><li>Finally, it creates a JSON response containing the error message and returns it as an Axum response.</li></ul><p>This code allows you to handle and respond to various types of errors in your Axum application, including internal server errors and errors related to request body parsing. It ensures that appropriate HTTP status codes and error messages are included in the responses to provide meaningful feedback to clients</p><h4><strong>Create repository</strong></h4><p>The goal of the repository is to deal with interactions between your application’s domain models (such as PostModel) and the database using the Diesel ORM.</p><p>In this repository for our posts, we will define the structs representing the database entities, the different functions to perform operations but also the adapters to transform our database entities into domain models.</p><p>We’ll also perform error handling using the PostError enum we have created in the previous section.</p><p>But first, let’s create<strong> our error handler for infra errors.</strong> It will be used to convert different types of error in a generic Infra error. We will need then to create a <strong>trait</strong> that will be implemented by the different types of errors encountered in our infra.</p><p>I’ll also add a simple utility to adapt directly the errors</p><p><strong>src/infra/errors.rs</strong></p><pre>use std::fmt;<br>use deadpool_diesel::InteractError;<br><br>// Define a custom error type for infrastructure-related errors<br>#[derive(Debug)]<br>pub enum InfraError {<br>    InternalServerError, // Represents an internal server error<br>    NotFound,            // Represents a resource not found error<br>}<br><br>// Utility function to adapt errors of generic type T into InfraError<br>pub fn adapt_infra_error&lt;T: Error&gt;(error: T) -&gt; InfraError {<br>    error.as_infra_error()<br>}<br><br>// Implement the Display trait to customize how InfraError is displayed<br>impl fmt::Display for InfraError {<br>    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {<br>        match self {<br>            InfraError::NotFound =&gt; write!(f, &quot;Not found&quot;), // Display &quot;Not found&quot; for NotFound variant<br>            InfraError::InternalServerError =&gt; write!(f, &quot;Internal server error&quot;), // Display &quot;Internal server error&quot; for InternalServerError variant<br>        }<br>    }<br>}<br><br>// Define a custom Error trait for types that can be converted to InfraError<br>pub trait Error {<br>    fn as_infra_error(&amp;self) -&gt; InfraError;<br>}<br><br>// Implement the Error trait for diesel::result::Error<br>impl Error for diesel::result::Error {<br>    fn as_infra_error(&amp;self) -&gt; InfraError {<br>        match self {<br>            diesel::result::Error::NotFound =&gt; InfraError::NotFound, // Map NotFound to InfraError::NotFound<br>            _ =&gt; InfraError::InternalServerError, // Map other errors to InfraError::InternalServerError<br>        }<br>    }<br>}<br><br>// Implement the Error trait for deadpool_diesel::PoolError<br>impl Error for deadpool_diesel::PoolError {<br>    fn as_infra_error(&amp;self) -&gt; InfraError {<br>        InfraError::InternalServerError // Map all PoolError instances to InfraError::InternalServerError<br>    }<br>}<br><br>// Implement the Error trait for InteractError<br>impl Error for InteractError {<br>    fn as_infra_error(&amp;self) -&gt; InfraError {<br>        InfraError::InternalServerError // Map all InteractError instances to InfraError::InternalServerError<br>    }<br>}</pre><p><strong>src/infra/repositories/post_repository.rs</strong></p><pre><br>use diesel::{<br>    ExpressionMethods, Insertable, PgTextExpressionMethods, QueryDsl, Queryable, RunQueryDsl,<br>    Selectable, SelectableHelper,<br>};<br>use serde::{Deserialize, Serialize};<br>use uuid::Uuid;<br><br><br>use crate::domain::models::post::PostModel;<br>use crate::infra::db::schema::posts;<br>use crate::infra::errors::{adapt_infra_error, InfraError};<br><br>// Define a struct representing the database schema for posts<br>#[derive(Serialize, Queryable, Selectable)]<br>#[diesel(table_name = posts)] // Use the &#39;posts&#39; table<br>#[diesel(check_for_backend(diesel::pg::Pg))] // Check compatibility with PostgreSQL<br>pub struct PostDb {<br>    pub id: Uuid,<br>    pub title: String,<br>    pub body: String,<br>    pub published: bool,<br>}<br><br>// Define a struct for inserting new posts into the database<br>#[derive(Deserialize, Insertable)]<br>#[diesel(table_name = posts)] // Use the &#39;posts&#39; table<br>pub struct NewPostDb {<br>    pub title: String,<br>    pub body: String,<br>    pub published: bool,<br>}<br><br>// Define a struct for filtering posts<br>#[derive(Deserialize)]<br>pub struct PostsFilter {<br>    published: Option&lt;bool&gt;,<br>    title_contains: Option&lt;String&gt;,<br>}<br><br>// Function to insert a new post into the database<br>pub async fn insert(<br>    pool: &amp;deadpool_diesel::postgres::Pool,<br>    new_post: NewPostDb,<br>) -&gt; Result&lt;PostModel, InfraError&gt; {<br>    // Get a database connection from the pool and handle any potential errors<br>    let conn = pool.get().await.map_err(adapt_infra_error)?;<br><br>    // Insert the new post into the &#39;posts&#39; table, returning the inserted post<br>    let res = conn<br>        .interact(|conn| {<br>            diesel::insert_into(posts::table)<br>                .values(new_post)<br>                .returning(PostDb::as_returning()) // Return the inserted post<br>                .get_result(conn)<br>        })<br>        .await<br>        .map_err(adapt_infra_error)?<br>        .map_err(adapt_infra_error)?;<br><br>    // Adapt the database representation to the application&#39;s domain model<br>    Ok(adapt_post_db_to_post(res))<br>}<br><br>// Function to retrieve a post from the database by its ID<br>pub async fn get(<br>    pool: &amp;deadpool_diesel::postgres::Pool,<br>    id: Uuid,<br>) -&gt; Result&lt;PostModel, InfraError&gt; {<br>    // Get a database connection from the pool and handle any potential errors<br>    let conn = pool.get().await.map_err(adapt_infra_error)?;<br><br>    // Query the &#39;posts&#39; table to retrieve the post by its ID<br>    let res = conn<br>        .interact(move |conn| {<br>            posts::table<br>                .filter(posts::id.eq(id))<br>                .select(PostDb::as_select()) // Select the post<br>                .get_result(conn)<br>        })<br>        .await<br>        .map_err(adapt_infra_error)?<br>        .map_err(adapt_infra_error)?;<br><br>    // Adapt the database representation to the application&#39;s domain model<br>    Ok(adapt_post_db_to_post(res))<br>}<br><br>// Function to retrieve a list of posts from the database with optional filtering<br>pub async fn get_all(<br>    pool: &amp;deadpool_diesel::postgres::Pool,<br>    filter: PostsFilter,<br>) -&gt; Result&lt;Vec&lt;PostModel&gt;, InfraError&gt; {<br>    // Get a database connection from the pool and handle any potential errors<br>    let conn = pool.get().await.map_err(adapt_infra_error)?;<br><br>    // Build a dynamic query for retrieving posts<br>    let res = conn<br>        .interact(move |conn| {<br>            let mut query = posts::table.into_boxed::&lt;diesel::pg::Pg&gt;();<br><br>            // Apply filtering conditions if provided<br>            if let Some(published) = filter.published {<br>                query = query.filter(posts::published.eq(published));<br>            }<br><br>            if let Some(title_contains) = filter.title_contains {<br>                query = query.filter(posts::title.ilike(format!(&quot;%{}%&quot;, title_contains)));<br>            }<br><br>            // Select the posts matching the query<br>            query.select(PostDb::as_select()).load::&lt;PostDb&gt;(conn)<br>        })<br>        .await<br>        .map_err(adapt_infra_error)?<br>        .map_err(adapt_infra_error)?;<br><br>    // Adapt the database representations to the application&#39;s domain models<br>    let posts: Vec&lt;PostModel&gt; = res<br>        .into_iter()<br>        .map(|post_db| adapt_post_db_to_post(post_db))<br>        .collect();<br><br>    Ok(posts)<br>}<br><br>// Function to adapt a database representation of a post to the application&#39;s domain model<br>fn adapt_post_db_to_post(post_db: PostDb) -&gt; PostModel {<br>    PostModel {<br>        id: post_db.id,<br>        title: post_db.title,<br>        body: post_db.body,<br>        published: post_db.published,<br>    }<br>}</pre><p>Now that we’ve got our database interactions sorted with the repository, it’s time to dive into the fun stuff: handling incoming HTTP requests and crafting responses. In the next sections, we’ll explore the handlers that’ll make our API shine.. This is where things really start to get exciting, as we connect our data layer with the Axum framework to create a fully functional and secure API.</p><h4>Create our handlers</h4><p>Handlers play a crucial role in web applications, and their primary goal is to handle incoming HTTP requests and generate appropriate HTTP responses. Here’s an explanation of the goal of handlers and how they interact with the repository</p><p>The interaction between handlers and the repository is a crucial part of building web applications.</p><p><strong>create_post.rs</strong></p><pre>// Import necessary modules and types<br>use axum::extract::State;<br>use axum::Json;<br><br>// Import internal modules and types<br>use crate::domain::models::post::PostError;<br>use crate::handlers::posts::{CreatePostRequest, PostResponse};<br>use crate::infra::repositories::post_repository;<br><br><br>// This is a placeholder to extract JSON data from the request body.<br>use crate::utils::JsonExtractor;<br>use crate::AppState;<br><br>// Define the handler function for creating a new post<br>pub async fn create_post(<br>    State(state): State&lt;AppState&gt;,                  // Extract the application state from the request<br>    JsonExtractor(new_post): JsonExtractor&lt;CreatePostRequest&gt;,  // Extract JSON data from the request body<br>) -&gt; Result&lt;Json&lt;PostResponse&gt;, PostError&gt; {<br>    // Create a NewPostDb instance with data from the JSON request<br>    let new_post_db = post_repository::NewPostDb {<br>        title: new_post.title,<br>        body: new_post.body,<br>        published: false, // Set the initial &#39;published&#39; status to false<br>    };<br><br>    // Insert the new post into the database using the repository<br>    let created_post = post_repository::insert(&amp;state.pool, new_post_db)<br>        .await<br>        .map_err(PostError::InfraError)?;  // Handle potential infrastructure errors<br><br>    // Create a PostResponse instance from the newly created post<br>    let post_response = PostResponse {<br>        id: created_post.id,<br>        title: created_post.title,<br>        body: created_post.body,<br>        published: created_post.published,<br>    };<br><br>    // Return the response as JSON with a success status<br>    Ok(Json(post_response))<br>}</pre><ul><li>State(state): This line extracts the AppState from the application&#39;s state, which contains the database connection pool and other shared application data.</li><li>JsonExtractor(new_post): This line extracts the JSON data from the request body and deserializes it into a CreatePostRequest struct.<strong> The extractor will be explained in a following section</strong></li><li>The code then creates a NewPostDb instance based on the extracted request data, setting the initial &#39;published&#39; status to false.</li><li>It uses the post_repository::insert function to insert the new post into the database, handling potential infrastructure errors.</li><li>After successfully inserting the post, it constructs a PostResponse from the created post&#39;s data.</li><li>Finally, it returns the PostResponse as JSON with a success status in an Ok result, making it ready to be sent as a response to the client&#39;s request.</li></ul><p><strong>get_post.rs</strong></p><pre>// Import necessary modules and types<br>use axum::extract::State;<br>use axum::Json;<br>use uuid::Uuid;<br><br>// Import internal modules and types<br>use crate::domain::models::post::{PostError, PostModel};<br>use crate::handlers::posts::PostResponse;<br>use crate::infra::errors::InfraError;<br>use crate::infra::repositories::post_repository;<br><br>// Import PathExtractor for extracting the post_id from the request path<br>use crate::utils::PathExtractor;<br>use crate::AppState;<br><br>// Define the handler function for retrieving a specific post by its ID<br>pub async fn get_post(<br>    State(state): State&lt;AppState&gt;,                    // Extract the application state from the request<br>    PathExtractor(post_id): PathExtractor&lt;Uuid&gt;,       // Extract the post_id from the request path<br>) -&gt; Result&lt;Json&lt;PostResponse&gt;, PostError&gt; {<br>    // Use the post_repository to fetch the post based on its ID<br>    let post = post_repository::get(&amp;state.pool, post_id)<br>        .await<br>        .map_err(|db_error| match db_error {<br>            // Map infrastructure errors to custom PostError types<br>            InfraError::InternalServerError =&gt; PostError::InternalServerError,<br>            InfraError::NotFound =&gt; PostError::NotFound(post_id),<br>        })?;<br><br>    // Convert the retrieved PostModel to a PostResponse<br>    Ok(Json(adapt_post_to_post_response(post)))<br>}<br><br>// Helper function to adapt a PostModel to a PostResponse<br>fn adapt_post_to_post_response(post: PostModel) -&gt; PostResponse {<br>    PostResponse {<br>        id: post.id,<br>        title: post.title,<br>        body: post.body,<br>        published: post.published,<br>    }<br>}</pre><ul><li>State(state): This line extracts the AppState from the application&#39;s state, which contains the database connection pool and other shared application data.</li><li>PathExtractor(post_id): This line extracts the post_id from the request&#39;s path. The PathExtractor is used to extract data from the request path, in this case, the unique identifier of the post.</li><li>The code then uses the post_repository::get function to fetch the post from the database based on the provided post_id. It also handles potential database errors and maps them to custom PostError types.</li><li>The adapt_post_to_post_response function converts the retrieved PostModel to a PostResponse to prepare it for the JSON response.</li><li>Finally, it returns the PostResponse as JSON in an Ok result, making it ready to be sent as a response to the client&#39;s request.</li></ul><p><strong>list_posts.rs</strong></p><pre>// Import necessary modules and types<br>use axum::extract::{Query, State};<br>use axum::Json;<br><br>// Import internal modules and types<br>use crate::domain::models::post::{PostError, PostModel};<br>use crate::handlers::posts::{ListPostsResponse, PostResponse};<br>use crate::infra::repositories::post_repository::{get_all, PostsFilter};<br>use crate::AppState;<br><br>// Define the handler function for listing posts with optional query parameters<br>pub async fn list_posts(<br>    State(state): State&lt;AppState&gt;,      // Extract the application state from the request<br>    Query(params): Query&lt;PostsFilter&gt;,  // Extract query parameters for filtering posts<br>) -&gt; Result&lt;Json&lt;ListPostsResponse&gt;, PostError&gt; {<br>    // Use the `get_all` function to retrieve a list of posts based on the provided query parameters<br>    let posts = get_all(&amp;state.pool, params)<br>        .await<br>        .map_err(|_| PostError::InternalServerError)?;<br><br>    // Convert the retrieved list of PostModel instances to a ListPostsResponse<br>    Ok(Json(adapt_posts_to_list_posts_response(posts)))<br>}<br><br>// Helper function to adapt a single PostModel to a PostResponse<br>fn adapt_post_to_post_response(post: PostModel) -&gt; PostResponse {<br>    PostResponse {<br>        id: post.id,<br>        title: post.title,<br>        body: post.body,<br>        published: post.published,<br>    }<br>}<br><br>// Helper function to adapt a list of PostModel instances to a ListPostsResponse<br>fn adapt_posts_to_list_posts_response(posts: Vec&lt;PostModel&gt;) -&gt; ListPostsResponse {<br>    // Map each PostModel to a PostResponse and collect them into a Vec&lt;PostResponse&gt;<br>    let posts_response: Vec&lt;PostResponse&gt; =<br>        posts.into_iter().map(adapt_post_to_post_response).collect();<br><br>    // Create a ListPostsResponse containing the list of PostResponses<br>    ListPostsResponse {<br>        posts: posts_response,<br>    }<br>}</pre><ul><li>State(state): This line extracts the AppState from the application&#39;s state, which contains the database connection pool and other shared application data.</li><li>Query(params): This line extracts query parameters from the request. In this case, it extracts the PostsFilter struct, which can contain parameters like published and title_contains for filtering posts.</li><li>The code then uses the get_all function to retrieve a list of posts from the database based on the provided query parameters. It also handles potential database errors and maps them to a custom PostError type.</li><li>The adapt_post_to_post_response function is used to convert a single PostModel instance to a PostResponse.</li><li>The adapt_posts_to_list_posts_response function converts a list of PostModel instances to a ListPostsResponse. It does this by mapping each PostModel to a PostResponse and collecting them into a vector.</li><li>Finally, it returns the ListPostsResponse as JSON in an Ok result, making it ready to be sent as a response to the client&#39;s request. This handler allows clients to list posts and potentially filter them based on query parameters.</li><li>Handle post creation and querying from our router</li></ul><h4>Update the router with our new handlers</h4><p>Now, we have created our handlers, our models from the domain, and our repositories from the infra, we can finally update our router to link every part of the application.</p><p>Let’s add our three different route in a new nested router : posts_routes</p><pre>use axum::{<br>    http::StatusCode,<br>    response::IntoResponse,<br>    routing::{get, post},<br>    Router,<br>};<br><br>// Import handlers for post-related operations<br>use crate::handlers::posts::{create_post, get_post, list_posts};<br>// Import the application state<br>use crate::AppState;<br><br>// Function to create the main application router<br>pub fn app_router(state: AppState) -&gt; Router {<br>    Router::new()<br>        // Define the root route<br>        .route(&quot;/&quot;, get(root))<br>        // Nest post-related routes under &quot;/v1/posts&quot;<br>        .nest(&quot;/v1/posts&quot;, posts_routes(state.clone()))<br>        // Define a fallback handler for 404 errors<br>        .fallback(handler_404)<br>        // Attach the application state to the router<br>        .with_state(state)<br>}<br><br>// Handler for the root route<br>async fn root() -&gt; &amp;&#39;static str {<br>    &quot;Server is running!&quot;<br>}<br><br>// Handler for 404 Not Found errors<br>async fn handler_404() -&gt; impl IntoResponse {<br>    (<br>        StatusCode::NOT_FOUND,<br>        &quot;The requested resource was not found&quot;,<br>    )<br>}<br><br>// Function to define post-related routes<br>fn posts_routes(state: AppState) -&gt; Router&lt;AppState&gt; {<br>    Router::new()<br>        // Route for creating a new post (POST /v1/posts)<br>        .route(&quot;/&quot;, post(create_post))<br>        // Route for listing all posts (GET /v1/posts)<br>        .route(&quot;/&quot;, get(list_posts))<br>        // Route for getting a specific post by ID (GET /v1/posts/:id)<br>        .route(&quot;/{id}&quot;, get(get_post))<br>        // Attach the application state to the posts router<br>        .with_state(state)<br>}</pre><h4><strong>Custom axum extractors to improve error handling</strong></h4><p>Custom extractors allow you to define structured input data extraction, validation, and transformation logic, making it easier to handle and report errors effectively.</p><p>By creating custom extractors, you can:</p><ol><li><strong>Encapsulate Input Processing:</strong> Custom extractors encapsulate the process of extracting data from incoming requests. This helps keep your handler functions clean and focused on application logic rather than data validation.</li><li><strong>Centralize Error Handling:</strong> You can implement error handling and validation logic within the custom extractor itself. This means that any errors related to input data can be captured and reported in a standardized way.</li><li><strong>Improve Code Reusability:</strong> Once defined, custom extractors can be reused across multiple routes and handlers. This promotes code reusability and reduces duplication of error handling logic.</li><li><strong>Enhance Readability:</strong> Custom extractors make your route and handler functions more readable by abstracting away low-level details of data extraction and validation.</li><li><strong>Provide Clear Error Responses:</strong> When an error occurs during data extraction, custom extractors can generate clear error responses with appropriate HTTP status codes and error messages. This helps clients understand and react to errors effectively.</li></ol><p>In the previous sections, we have defined two custom extractors, why that ?</p><p>It it because we want to adapt the<strong> errors coming from the serialization of json and the parsing of params</strong> to be transformed into AppErrors.</p><p>In our case, we are using already existing extractors coming from Axum : Json() andPath()</p><p>Within the official axum-macros crate, you can find a very useful macro that can help us define custom-extractors that derive from existing ones to improve error handling : useFromRequest.</p><p>Let’s write our two custom extractors :</p><p><strong>json_extractor.rs</strong></p><pre>// Import necessary modules and types<br>use axum::extract::rejection::JsonRejection;<br>use axum_macros::FromRequest;<br><br>// Import internal AppError type<br>use crate::errors::AppError;<br><br>// Define a custom extractor for JSON data<br>#[derive(FromRequest)]<br>#[from_request(via(axum::Json), rejection(AppError))]  // Derive the FromRequest trait with specific configuration<br>pub struct JsonExtractor&lt;T&gt;(pub T);<br><br>// Implement the conversion from JsonRejection to AppError<br>impl From&lt;JsonRejection&gt; for AppError {<br>    fn from(rejection: JsonRejection) -&gt; Self {<br>        // Convert the JsonRejection into a BodyParsingError with the rejection message<br>        AppError::BodyParsingError(rejection.to_string())<br>    }<br>}</pre><ul><li>The code defines a custom extractor JsonExtractor&lt;T&gt; for JSON data. This extractor is designed to extract data of type T from JSON request bodies.</li><li>The #[derive(FromRequest)] attribute macro is used to automatically implement the FromRequest trait for the JsonExtractor&lt;T&gt;. This trait allows Axum to use this custom extractor in route handlers.</li><li>In the #[from_request(via(axum::Json), rejection(AppError))] attribute, the extractor is configured to work with JSON data using axum::Json. Additionally, it specifies that rejections should be handled using the AppError type.</li><li>The impl From&lt;JsonRejection&gt; for AppError block implements the conversion from JsonRejection (which can occur when JSON parsing fails) to the custom AppError type.</li><li>Inside the implementation, it creates an AppError::BodyParsingError variant with the rejection message obtained from the JsonRejection. This allows for consistent error handling and reporting when JSON parsing fails.</li></ul><p><strong>path_extractor.rs</strong></p><pre>use axum::extract::rejection::PathRejection;<br>use axum_macros::FromRequestParts;<br><br>use crate::errors::AppError;<br><br>#[derive(FromRequestParts, Debug)]<br>#[from_request(via(axum::extract::Path), rejection(AppError))]<br>pub struct PathExtractor&lt;T&gt;(pub T);<br><br>impl From&lt;PathRejection&gt; for AppError {<br>    fn from(rejection: PathRejection) -&gt; Self {<br>        AppError::BodyParsingError(rejection.to_string())<br>    }<br>}</pre><h3>What is coming next ?</h3><p>Thanks to everyone for taking the time to read this tutorial! In this post, we’ve covered the foundations of building a real-world backend application in Rust using Axum and Diesel, following Domain-Driven Design principles. We’ve explored the creation of modular code, database configuration, and the implementation of handlers for various API endpoints. But we’re not done yet!</p><p>In the upcoming sections, we’ll dive into two critical aspects of our application. First, we’ll explore how to make <strong>testing</strong> in Axum, to deploy our Rust backend using <strong>Docker</strong>, ensuring that it’s ready for production use. Then, we’ll take a closer look at adding <strong>OAuth</strong> authentication to enhance the security and user management of our application.</p><p>So, stay tuned for the next parts of this series, where we’ll continue to build and enhance our backend application. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b25cf5c65bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>