List Endpoint

Learn to create an endpoint to list products.

We'll cover the following...

Basic list handler

We need to show a list of products to the user. We already have the method implemented to obtain them from the database; now, we can use it for our endpoint.

Press + to interact
mod product;
use actix_web::{web, App, HttpServer, Responder, HttpResponse, Result};
use diesel::sqlite::SqliteConnection;
use product::list_products;
use ::shoe_store::models::*;
use ::shoe_store::establish_connection;
// Our list endpoint, just make a call to list_product and pattern match
// the result, if everything is ok we're supposed to return a list of products
// as a json object with web::Json(products), otherise just return a 500 error.
async fn product_list(conn: web::Data<SqliteConnection>)
-> Result<impl Responder> {
match list_products(&conn) {
Ok(products) => Ok(web::Json(products)),
Err(error) => Err(actix_web::error::ErrorInternalServerError(error))
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.data(establish_connection()) // This is a data wrapper, where we passed our database connection
.route("products", web::get().to(product_list)) // our route to list products
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}

In the above code, we return a JSON formatted list ...