Actix/Diesel API not responding to requests from Postman

My code seems to be ok, as it properly compiles and is quite simple. But when I run my app with cargo run, even though the program executes properly and outputs some debug printlns, it won’t answer to any request.

This is my main.rs:

use actix_web::{web, App, HttpServer};
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::sqlite::SqliteConnection;
use dotenvy::dotenv;

#[path = "api/books/books_handlers.rs"]
mod books_handlers;
#[path = "api/books_relationships/books_relationships_handlers.rs"]
mod books_relationships_handlers;
mod models;
mod routes;
mod schema;
mod logger;

#[actix_rt::main]
async fn main() -> std::io::Result<()> {

    // Load .env file and set initialization variables
    dotenv().ok();
    std::env::set_var("RUST_LOG", "actix_web=debug");
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");


    // Create db connection pool with SQLite
    let manager = ConnectionManager::<SqliteConnection>::new(database_url);
    let pool: Pool<ConnectionManager<SqliteConnection>> = r2d2::Pool::builder()
        .build(manager)
        .expect("Failed to create pool.");

    // Start HTTP server and register routes
    println!("Starting server at http://localhost:8080");
    HttpServer::new(move || {
        App::new()
            .app_data(pool.clone())
            // Book class
            .route("/create_book", web::post().to(books_handlers::create_book_handler))
            .route("/list_books", web::get().to(books_handlers::list_books_handler))
            .route("/get_book/{id}", web::post().to(books_handlers::read_book_by_id_handler))
            .route("/update_book/{id}", web::put().to(books_handlers::update_book_handler))
            .route("/delete_book/{id}", web::delete().to(books_handlers::delete_book_handler))
            // BookRelationships class
            .route("/create_book_relationship", web::post().to(books_relationships_handlers::create_book_relationship_handler))
            .route("/list_book_relationships", web::get().to(books_relationships_handlers::list_books_handler))
            .route("/get_book_relationship/{id}", web::post().to(books_relationships_handlers::read_book_by_id_handler))
            .route("/update_book_relationship/{id}", web::put().to(books_relationships_handlers::update_book_handler))
            .route("/delete_book_relationship/{id}", web::delete().to(books_relationships_handlers::delete_book_handler))

        })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

This is the first handler, the one I’m trying with Postman:

pub async fn create_book_handler(book_data: web::Json<Book>, pool: web::Data<DbPool>) -> HttpResponse {
    println!("create_book_handler: {:#?}", book_data);  // <-- this never gets executed
    let result = books_dao::create_book(book_data, pool).await;
    match result {
        Ok(book) => {
            println!("create_book_handler, OK. Book: {:#?}", book);
            HttpResponse::Ok()
            .content_type(ContentType::json())
            .json(&book)
        },
        Err(err) => {
            println!("create_book_handler, ERROR: {:#?}", err);
            log(LogType::Error, err.to_string());
            HttpResponse::InternalServerError()
                .content_type(ContentType::json())
                .body("{err: 'Unable to insert book into database'")
        }
    }
}

Then the code executes this function, calling Diesel and altering the DB:

pub async fn create_book(book: web::Json<Book>, pool: web::Data<DbPool>) -> Result<usize, Error> {
    let mut conn = pool
        .get()
        .expect("Failed to get database connection from pool");

    diesel::insert_into(books::table)
        .values(book.into_inner())
        .execute(&mut conn)
}

But the problem seems to be even before: not even the println! at the beginning of the handler get executed. When I start the app and send a POST request to http://127.0.0.1:8080/create_book, I get the following error in Postman:

Requested application data is not configured correctly. View/enable debug logs for more details.

Am I sending the requests in a wrong way, or is the API malfunctioning?

>Solution :

The DbPool is wrapped incorrectly. It should look like

...
    App::new()
            .app_data(actix_web::web::Data::new(pool.clone()))
...

This correctly wraps the DB Pool in the smart pointer that the route handlers can then use across your application

Leave a Reply