Search code examples
postgresqlrustjsonbactix-web

How to create a POST method using Actix on Rust?


I'm investigating a way to port a micro-service from Ruby to Rust. My framework of choice is Actix (but anyone else would work without issues). Now, I'm trying to understand how to create a POST method, that receive two JSON as input. Those two JSON, have two completely different structures and within the structure could have different objects (JSON object) to later be stored later in two PostgreSQL JSONB fields.

Any hints on how to structure the function and the related structs? I thought to receive it as Strings, but I am not sure its the right thing to do.


Solution

  • It's very easy. Just use a struct with regular fields and two separate struct declarations for the two types of data.

     struct FirstT {}
     struct SecondT {}
    
     #[derive(Serialize, Deserialize,Debug)]
     struct PostData {
       first_t: FirstT,
       second_t: SecondT 
     }
    
    
     
     async fn submit(data: web::Json<PostData>) -> HttpResponse {
         //use data.first_t data.second_t
     }
    
     #[actix_rt::main]
     async fn main() -> std::io::Result<()> {
    
      HttpServer::new(|| {
         App::new()
          .data(web::JsonConfig::default().limit(4096)) 
          .service(web::resource("/submit").route(web::post().to(submit)))
      })
      .bind("127.0.0.1:8000")?
      .run()
      .await
    }