Creating a Rest API with Spring Boot

We've seen the power of Spring and Spring Boot. So, let's use it without any further delay. We will build a RESTful web service that will return a Todo object. We will further enhance this project in the next chapter, where we will add Todo and fetch a list of Todo from the database. We will use JPA and Hibernate along with Spring for that purpose.

When we are done with this example, we should get the following response:

Cropped screenshot of browser output

So, let's start by creating a new project. You can use http://start.spring.io/ or you can use IntelliJ IDEA as well to create a new project.

After you have created the new project, you will see that there's an Application class; don't give much focus to it, it's there in almost all Spring Boot applications. We need to create a new class for Todo, as follows:

    data class Todo ( 
        var id:Int = 0, 
        var todoDescription:String, 
        var todoTargetDate:String, 
        var status:String 
    ) 

A REST API requires us to create RestController, which would be the endpoint for API requests, so here's our RestController:

    @RestController@RequestMapping("/api") 
    class TodoController { 
      @RequestMapping("/get_todo") 
      fun getTodo() = Todo(1,"TODO Project","31/11/2017","Running") 
   } 

Study this small class carefully. First, we annotated our class with @RestController and @RequestMapping. The purpose of them is simple @RestController denotes that this class will act as a Controller, that is, all API requests should pass through this class, @RequestMapping("/api") denotes that the URL of this class will have an /api suffix after your base URL (note that the URL in the screenshot is http://127.0.0.1:8080/api/get_todo). We can skip the second annotation if we want for this class.

Then, we have the getTodo() function; the @RequestMapping annotation is required for this method as it will define the endpoint. This method is also simple—it just returns a new object of Todo, statically created.

What? Are you expecting anything more? Sorry to disappoint you, but we are done with the API. You can just run the project and hit http://127.0.0.1:8080/api/get_todo to get the following JSON response:

    {"id":1,"todoDescription":"TODO   
Project","todoTargetDate":"31/11/2017","status":"Running"}

Isn't it simple enough?

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

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