Search⌘ K

Update and Delete Endpoint

Explore how to implement update and delete endpoints in Rust for backend development. Understand creating simple RESTful routes, handling product updates and deletions, and writing tests to ensure functionality and reliability.

We'll cover the following...

Update

If we want to update a product, we need the id of the product to be updated and the data to be mutated. The code is as follows.

Rust 1.40.0
use actix_web::{web, Responder, HttpResponse,HttpServer,App};
use diesel::sqlite::SqliteConnection;
use diesel::{RunQueryDsl, QueryDsl, Connection};
use anyhow::Result;
// Our product_update just receive as parameter a serialized product and
// return a 200 response if everything works, otherwise an internal server error.
async fn product_update(id: web::Path<i32>, product: web::Json<FormProduct>, conn: web::Data<SqliteConnection>)
-> actix_web::Result<impl Responder> {
match update_product(*id, product.clone(), &conn) {
Ok(_) => Ok(HttpResponse::Ok()),
Err(error) => Err(actix_web::error::ErrorInternalServerError(error))
}
}
use ::shoe_store::establish_connection;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.data(establish_connection())
.route("products/{id}", web::put().to(product_update))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}

We try to make endpoints as simple and straightforward ...