#actix-web #json #actix

actix-json-response

A helper type for json responses with Actix-web

4 releases

0.1.3 Apr 16, 2022
0.1.2 Apr 16, 2022
0.1.1 Apr 16, 2022
0.1.0 Apr 16, 2022

#56 in #actix

Download history 49/week @ 2024-07-02 61/week @ 2024-07-09 1/week @ 2024-07-16 65/week @ 2024-07-23 75/week @ 2024-07-30 101/week @ 2024-08-06 95/week @ 2024-08-13 31/week @ 2024-08-20 4/week @ 2024-08-27 7/week @ 2024-09-03 107/week @ 2024-09-10 122/week @ 2024-09-17 182/week @ 2024-09-24 37/week @ 2024-10-01 22/week @ 2024-10-15

274 downloads per month

MIT/Apache

7KB

Actix Json Response

A library that exposes a helper type for Json responses in Actix-Web.

Continuous Integration license-badge rust-version-badge

Getting started

How to install

Add actix-json-response to your dependencies:

[dependencies]
# ...
actix-web = "4"
actix-json-response = "0.1"

Quickstart

actix-json-response exposes the JsonResponse type which implements Actix's Responder trait. It is generic and receives a type parameter that must implement Serde's Serialize trait:

use actix_web::{get, web, Result};
use actix_json_response::JsonResponse;
use serde::Serialize;

#[derive(Serialize)]
struct MyObj {
    name: String,
}

#[get("/a/{name}")]
async fn index(name: web::Path<String>) -> Result<JsonResponse<MyObj>> {
    let my_obj = MyObj {
        name: name.to_string(),
    };
    Ok(my_obj.into())
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};

    HttpServer::new(|| App::new().service(index))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

By default, the response will have status code 200. If you need the response to have a different status code, you can use the with_status_code method that receives an Actix's StatusCode:

use actix_web::http::StatusCode;

#[get("/a/{name}")]
async fn index(name: web::Path<String>) -> Result<JsonResponse<MyObj>> {
    let my_obj = MyObj {
        name: name.to_string(),
    };
    Ok(JsonResponse::from(my_obj).with_status_code(StatusCode::CREATED)) // The response will have status code 201 in this case
}

License

Distributed under the terms of MIT license and Apache license.

Dependencies

~14–25MB
~434K SLoC