api rust in rust

To create an API in Rust, you can use the Hyper library, which provides a low-level HTTP and HTTP/2 client and server support.

Here is a simple example of creating a GET endpoint using Hyper:

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::rt::Future;
use hyper::service::service_fn_ok;

fn main() {
    let addr = ([0, 0, 0, 0], 3000).into();

    let service = || {
        service_fn_ok(|_req: Request<Body>| {
            Response::new(Body::from("Hello, World!"))
        })
    };

    let server = Server::bind(&addr)
        .serve(service)
        .map_err(|e| eprintln!("server error: {}", e));

    hyper::rt::run(server);
}
453 chars
20 lines

In this example, we define an address to bind our server to and create a service with a closure that always returns a 200 OK response with a message. We then create a Server instance by binding it to our address and serving our service. Finally, we use hyper::rt::run to handle incoming requests.

You can build on this example by creating more complex routes and handling other HTTP methods. Hyper also supports adding request and response headers, handling errors, and asynchronous processing.

Additionally, there are many Rust web frameworks that provide higher-level abstractions for building APIs, such as Iron, Rocket, and Warp.

gistlibby LogSnag