Perform the following steps to implement this recipe:
- Open the main.rs file in the src directory in your preferred text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Creating a simple REST API
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 28 April 17
//-- #########################
- Import the installed nickel crate by using the extern keyword:
#[macro_use]
extern crate nickel;
use nickel::{Nickel, JsonBody, HttpRouter, Request,
Response, MiddlewareResult, MediaType};
- Define the main function in which we declare the server instance:
fn main() {
let mut server = Nickel::new();
let mut router = Nickel::router();
- Define the GET endpoint:
router.get("/users", middleware! { |request, response|
format!("Hello from GET /users")
});
- Define the POST endpoint:
router.post("/users/new", middleware! { |request,
response|
format!("Hello from POST /users/new")
});
- Define the DELETE endpoint:
router.delete("/users/:id", middleware! { |request,
response|
format!("Hello from DELETE /users/:id")
});
- Declare the port at which the services will be started:
server.utilize(router);
server.listen("127.0.0.1:9000");
}
- Save the file and start the server with the following command from the root directory of the project:
cargo run
- We will get the following output on the successful execution of our code in the terminal:
We make a GET request to http://127.0.0.1:9000/users, which returns Hello from GET /users from the web service created using the nickel web application framework, as shown in the following screenshot:
We make a POST request to http://127.0.0.1:9000/users/new, which returns Hello from POST /users/new from the web service created using the nickel web application framework:
We make a DELETE request to http://127.0.0.1:9000/users/:id, which returns Hello from DELETE /users/:id from the web service created using the nickel web application framework: