How to do it...

Perform the following steps to implement this recipe:

  1. Open the main.rs file in the src directory in your preferred text editor.
  2. 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
//-- #########################
  1. Import the installed nickel crate by using the extern keyword:
        #[macro_use]
extern crate nickel;

use nickel::{Nickel, JsonBody, HttpRouter, Request,
Response, MiddlewareResult, MediaType};
  1. Define the main function in which we declare the server instance:
        fn main() {

let mut server = Nickel::new();
let mut router = Nickel::router();
  1. Define the GET endpoint:
        router.get("/users", middleware! { |request, response|

format!("Hello from GET /users")

});
  1. Define the POST endpoint:
        router.post("/users/new", middleware! { |request,
response|

format!("Hello from POST /users/new")

});
  1. Define the DELETE endpoint:
        router.delete("/users/:id", middleware! { |request,
response|

format!("Hello from DELETE /users/:id")

});
  1. Declare the port at which the services will be started:
        server.utilize(router);

server.listen("127.0.0.1:9000");
}
  1. Save the file and start the server with the following command from the root directory of the project:
    cargo run
  1. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.60.63