How to send an array with HttpResponse?

1.5k views Asked by At

Is there a way to send a vector (array) through a HttpResponse with actix_web?

I can send strings in the body completely fine and was hoping to send an array for the client to receive and store.

This is my currently used code snippet which responds with an error in the .body(data):

        let smembers_check = database::smembers(info.key).ok();
        if smembers_check != None
        {
            let data = smembers_check.unwrap();
            HttpResponse::Ok().body(data)
        }
        else
        {
            HttpResponse::Ok().body("")
        }

Is there a solution to this? Thanks in advance.

2

There are 2 answers

3
Prabhu E On BEST ANSWER

Return HttpResponse in handler signature and return data like this: HttpResponse::Ok().json(data)

0
Ili On

You can use serde to serialize / deserialize your db model (or any struct you want to return as json) and then you can use .json() on the HttpResponse

example:

pub async fn get_all_users(data: Data<AppState>) -> impl Responder {
  let users: Vec<Model> = User::find().all(&data.db).await.unwrap();
  HttpResponse::Ok().json(users)
}

On the user struct derive add the serialize / deserialize from serde, here's model example with sea-orm:

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "user")]
pub struct Model {
  #[sea_orm(primary_key, auto_increment = false)]
  pub id: Uuid,
  pub email: String,
  pub password: String,
}

the same can be applied to any rust struct you want to return as json