api in rust

To create an API in Rust, we can use different web frameworks like Actix-web, Rocket, Tide, Hyper, and many more. Here, we'll use Actix-web to create a simple API.

First, we need to add the Actix-web and serde dependencies to our Cargo.toml file:

main.rs
[dependencies]
actix-web = "3"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
101 chars
5 lines

Then, we can create a simple API that returns a JSON response. In this example, the API routes are defined in the routes function and the index function handles the incoming HTTP request and returns a JSON response:

main.rs
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Greeting {
    message: String,
}

#[get("/")]
async fn index() -> impl Responder {
    let greeting = Greeting {
        message: String::from("Hello, world!"),
    };
    HttpResponse::Ok().json(greeting)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
533 chars
24 lines

To run the API, we can use the following command:

main.rs
cargo run
10 chars
2 lines

This will start the API on http://localhost:8080/, and we can test it using any HTTP client or a web browser.

This example just scratches the surface of what you can do with Actix-web and Rust APIs. You can create more complex routes, handle different HTTP methods, read request parameters and bodies, and much more.

gistlibby LogSnag