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.rs101 chars5 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.rs533 chars24 lines
To run the API, we can use the following command:
main.rs10 chars2 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