part 3 in a full stack series
In Implementing JpaRepository for CRUD capabilities in your Spring Project we created our repository interface and service class. Now we need to make sure that we will be able to use the methods we defined when we begin to test using Postman.
This tutorial will walk through creation of a REST controller and the workings that Spring will do in order to build a RESTful web service. Then, looking ahead; a demo of using Postman to facilitate POST, READ, UPDATE and DESTROY methods, or, crud functions.
Postman is an API platform for building and using APIs. In it you can send requests to resources and be returned a result. We will learn how to create a controller to handle requests and create errors if a request was unable to be completed. Let’s get started in the application.
Information will be returned based on the type of request from a client. These will be requested via user interactions, which we will see how to build when we start the front end development. Before our application can handle requests and retrieve information we need to create our REST controller.
To understand what a REST controller is we need to understand what a REST web service is. REST is a web building style that defines functions and data as resources and provides operations that allow you to act on that data. Every resource is identified through its on URI, uniform resource identifier, usually a link on the web. The four operations used to act on resources are POST, GET, PUT, and DELETE. Most actions that a controller routes to resources will have one of those four operations. Spring allows the use annotations that provide metadata about the way it should build a service for us.
Navigate to the main package and in it create another package; continuing with the demo, this package will be com.dinner.Athletes.Controller. In the new controller package create a new class, AthletesController. The annotation spring gives for this is ‘@RestController’; put this above the class declaration. Spring also gives an annotation, ‘@RequestMapping’, that is used to map requests to classes and methods. This comes with an optional value argument that you can set to the base endpoint of your class or method. This will be “/athletes”.