Creare una API REST JSON in Rust e Actix
In questo articolo abbiamo visto come creare una semplice API in Rust con Actix.
Oggi aggiungiamo qualche pezzo, di cui il più interessante / utile è l'invio dell'output in formato JSON.
Queste sono le dipendenze da aggiungere a Cargo.toml:
[dependencies]
actix-web = "2.0"
actix-rt = "1.0"
serde = "1.0.106"
Rispetto all'altro articolo abbiamo aggiunto Serde.
Questo il codice Rust:
use actix_web::{web, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct MyObj {
name: String,
}
async fn index(obj: web::Path<MyObj>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(MyObj {
name: obj.name.to_string(),
}))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(
web::scope("/persone")
.route(r"/{name}", web::get().to(index))
)
})
.bind("127.0.0.1:8088")?
.run()
.await
}
Come vedete abbiamo una sola route, che richiede un nome.
Il tutto dentro ad uno scope; in breve gli scope servono per suddividere le api in "gruppi".
Inoltre abbiamo usato una struct per il nostro oggetto; adesso andate su http://localhost:8088/persone/mio_nome.
Enjoy!
rust actix cargo json serde
Commentami!