Search⌘ K
AI Features

List Endpoint

Explore how to implement a list endpoint in Rust using Actix Web, including handling query parameters for limiting results. Learn to modify backend methods and write tests to validate JSON responses, enhancing your Rust backend development skills.

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.

Rust 1.40.0
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 of products instead of ...