return a json response from a http server in rust

To return a JSON response from a HTTP server in Rust, you will need to follow these steps:

  1. Add the serde and serde_json dependencies to your project. You can do this by adding the following lines to your Cargo.toml file:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
85 chars
4 lines
  1. Create a struct that represents the response data. This struct must implement the Serialize trait from serde.
main.rs
use serde::{Serialize};

#[derive(Serialize)]
struct JsonResponse {
    message: String,
    status: String,
}
111 chars
8 lines
  1. Create a route handler that returns the JSON response. In this example, we're using the hyper crate to create a HTTP server.
main.rs
use hyper::{Body, Request, Response};
use hyper::header::CONTENT_TYPE;
use serde_json::to_string;

async fn json_response_handler(_: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    // Create a JSON response
    let response_data = JsonResponse {
        message: "Hello world".to_string(),
        status: "success".to_string(),
    };

    // Serialize the response data to JSON
    let response_json = to_string(&response_data).unwrap();

    // Create a HTTP response with the JSON data
    let mut response = Response::new(Body::from(response_json));

    // Set the content type header to application/json
    response.headers_mut().insert(CONTENT_TYPE, "application/json".parse().unwrap());

    Ok(response)
}
730 chars
23 lines
  1. Start the server and listen for incoming requests. In this example, we're using the tokio runtime to run the server.
main.rs
use hyper::service::{make_service_fn, service_fn};
use hyper::{Server, Body};

#[tokio::main]
async fn main() {
    let address = ([127, 0, 0, 1], 3000).into();

    let service = make_service_fn(|_| async {
        Ok::<_, hyper::Error>(service_fn(json_response_handler))
    });

    let server = Server::bind(&address).serve(service);

    println!("Listening on http://{}", address);

    if let Err(e) = server.await {
        eprintln!("Server error: {}", e);
    }
}
474 chars
20 lines

Now you can send a GET request to http://localhost:3000 and you should receive a JSON response that looks like:

main.rs
{
    "message": "Hello world",
    "status": "success"
}
58 chars
5 lines

related categories

gistlibby LogSnag