Creation of REST
services with Spring
Javier Cuenca
[email protected] 09-2023
Index
1. Creation of REST services
2. Web service testing
3. REST service parameters
4. REST with data formats
5. HTTP response management
6. Examples and Interesting links
24.07.23 Mondragon Unibertsitatea 2
1 Creation of
REST services
Introduction
• Spring is one of the most popular frameworks for application
development in the Java ecosystem.
• It provides a comprehensive infrastructure support for developing
Java applications. Spring handles the infrastructure so you can
focus on your application.
• The Spring Framework codifies formalized design patterns as
first-class objects that you can integrate into your own
application(s).
24.07.23 Mondragon Unibertsitatea 4
Introduction
• Spring provides the Spring Web API to develop web applications,
including REST services.
• The Spring Web API includes a set of annotations that enable to
create easily REST services.
• We will start creating a service that returns the string ‘Hello World’.
24.07.23 Mondragon Unibertsitatea 5
1- Creation of the project
• To create the project, go to https://start.spring.io/ web
page.
• Select the following options: Project: Maven, language: Java and
Spring Boot (version): 3.0.2.
24.07.23 Mondragon Unibertsitatea 6
1- Creation of the project
• Fill in the project data
24.07.23 Mondragon Unibertsitatea 7
1- Creation of the project
• Add the Spring Web dependency:
24.07.23 Mondragon Unibertsitatea 8
1- Creation of the project
• Click on the Generate Button and the zip file of the project will be
downloaded:
24.07.23 Mondragon Unibertsitatea 9
2- Web service development
• Unzip de downloaded folder and copy it to your workspace.
• Open the folder with Visual Studio Code.
24.07.23 Mondragon Unibertsitatea 10
2- Web service development
• Now we will create the Web service using the Spring Web package.
• The spring web package includes annotations to define the
resources and methods of the web service.
24.07.23 Mondragon Unibertsitatea 11
2- Web service development
• Create the RESTcontroller Java class. The REST controller is the
central artifact in the entire Web Tier of the RESTful API.
• The class must be annotated with the @Restcontroller annotation
to say that it will be a REST service.
24.07.23 Mondragon Unibertsitatea 12
2- Web service development
• To add the path of the service we use the @RequestMapping
annotation.
• Then we have to implement the service methods.
• We also must specify the method type (GET, POST, PUT, DELETE).
• And the resource path.
• For that, we have the following annotations:
• @GetMapping (GET method).
• @PostMapping (POST method).
• @PutMapping (PUT method)
• @DeleteMapping (DELETE method)
24.07.23 Mondragon Unibertsitatea 13
2- Web service development
• In this example the method will be GET.
REST Service
path
Resource
method
Method type Resource path
24.07.23 Mondragon Unibertsitatea 14
2- Web service development
• Taking this into account, the URL of the service will be this one:
http://localhost:8080/helloWorld/hello
Server Service Resource
24.07.23 Mondragon Unibertsitatea 15
2- Web service development
• Finally, run the project:
24.07.23 Mondragon Unibertsitatea 16
2- Web service development
• Finally, run the project:
• The web application will be listening by default at port 8080.
24.07.23 Mondragon Unibertsitatea 17
2 REST Service
testing
Rest service testing
• After developing and deploying the (Web) service there are several
ways to consume the data.
• By consuming the services, we test if they work correctly by analyzing
the responses received.
• Options:
• Test the URL directly in a browser.
• Web page
• Applications: Postman, SoapUI, JMeter, SOAPSonar, Wizdler
24.07.23 Mondragon Unibertsitatea 19
REST service testing
• Write URL in browser:
24.07.23 Mondragon Unibertsitatea 20
Postman
• It mainly allows us to create requests on web applications/services in
a very simple way.
• In this way, web services can be tested and their data consumed.
• Intuitive interface, easy to use and supports all types of HTTP
requests.
• Ideal for testing REST Web services.
• Download and instructions for use: https://www.postman.com
24.07.23 Mondragon Unibertsitatea 21
Postman
1. Create a new collection to save the requests:
24.07.23 Mondragon Unibertsitatea 22
Postman
2. Rename the collection:
24.07.23 Mondragon Unibertsitatea 23
Postman
3. Add a new request to the collection:
24.07.23 Mondragon Unibertsitatea 24
Postman
Operation type Resource URL
Status
24.07.23 Response Mondragon Unibertsitatea 25
3 REST Service
Parameters
REST service parameters
• We can modify the web service to include parameters in the URL.
• For instance, let´s modify our service to include our name in the
response, e.j., Hello Javier!
• To include parameters in the query, we have two annotations:
• @PathVariable
• @RequestParam
24.07.23 Mondragon Unibertsitatea 27
REST service parameters
• @PathVariable: it can be used to handle template variables in the
request URI path, and set them as method parameters.
Specifies
where is the
variable place
in the URL
path
Specifices the path varaible
24.07.23 Mondragon Unibertsitatea 28
REST service parameters
• @PathVariable: testing in browser
24.07.23 Mondragon Unibertsitatea 29
Exercise
• Create the helloWorldPath method. Pass a name as path
parameter and return “hello” + the name.
• The path of the method Will be /hello/name
• Test it in navigator and Postman.
24.07.23 Mondragon Unibertsitatea 30
REST service parameters
• @RequestParam: to extract query parameters, form parameters,
and even files from the request.
Specifices parameter that can be
included in the request
24.07.23 Mondragon Unibertsitatea 31
REST service parameters
• @RequestParam: testing in browser
24.07.23 Mondragon Unibertsitatea 32
REST service parameters
• @RequestParam: this annotation can be also useful get the values
of the parameters of an HTML form.
• This is very useful when we consume a REST service from an
HTML front-end.
24.07.23 Mondragon Unibertsitatea 33
Exercise
• Create the helloWorldRequest method. Pass a name as request
paramenter parameter and return “hello” + the name.
• The path of the method Will be /helloRequest
• Test it in the navigator and Postman.
24.07.23 Mondragon Unibertsitatea 34
4 REST with
data formats
REST with data formats
• In Spring we can configure REST services to return objects with in
different data formats (i.e., XML, JSON).
• We will develop another project: a REST Service that returns the
information about students:
• In XML format
• In JSON format.
24.07.23 Mondragon Unibertsitatea 36
REST with data formats (XML)
• To use XML, we can use the Jackson XML extension.
• We will create the project students_service.
• Once the project is created, we have to edit the pom.xml file to
include the Jackson XML package (enables object to XML data
transformation and vice versa).
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
24.07.23 Mondragon Unibertsitatea 37
REST with data formats (XML)
• We also need to add to the pom.xml file the Loombook extension to
allow enable data transformation from object to XML.
24.07.23 Mondragon Unibertsitatea 38
REST with data formats (XML)
• In the project we create the Student class.java.
We include the @Data
annotation to enable the
‘Student’ class data
transforming
24.07.23 Mondragon Unibertsitatea 39
REST with data formats (XML)
• We create the controller GET method to return the student data.
We use the
produces
annotation to
indicate that
the data is
returned in
XML format
Important: Now, the @GetMapping annotation includes two parameters
the path and the returned data type. Therefore, we have to use the value
annotation inside @GetMapping to indicate the path.
24.07.23 Mondragon Unibertsitatea 40
REST with data formats (XML)
• We create the controller GET method to return the student data.
We use the
produces
annotation to
indicate that
the data is
returned in
XML format
(the value is
the XML MIME
ResponseEntity represents the whole HTTP response: status code, type)
headers, and body. In this example we indicate that the Response body
will be a Student object
• The method content is shown in the next slide ->
24.07.23 Mondragon Unibertsitatea 41
REST with data formats (XML)
• In this example we create the student inside the method.
• In the response we indicate that the method return with the HTTP
status OK.
24.07.23 Mondragon Unibertsitatea 42
REST with data formats (XML)
• If we test in the navigator we see the student data in XML:
24.07.23 Mondragon Unibertsitatea 43
REST with data formats (JSON)
• Now we will create a REST method that returns the student data
in JSON.
• We do not any package in this case, because in Spring REST
services the data is returned by default in JSON format.
• Therefore, we only need to indicate in the method that we are
returning data in JSON format.
24.07.23 Mondragon Unibertsitatea 44
REST with data formats (JSON)
• This is the created method:
Indicates that the data is
returned in JSON format
24.07.23 Mondragon Unibertsitatea 45
REST with data formats (JSON)
• If we test in the navigator we see the student data in JSON:
24.07.23 Mondragon Unibertsitatea 46
Exercise
• Download from Mudle the rest_helloworld project.
• Open and execute it.
• Test the getStudentXML and getStudentJSON methods with
Postman.
24.07.23 Mondragon Unibertsitatea 47
Receiving data in different formats
• REST methods not only can return XML and JSON data but
also receive parameters represented in these data formats.
• To indicate that a method consumes data objects in different
formats (i.e., JSON) data we use the consumes annotation.
• We also use the @RequestBody annotation if the parameter is
an object. Because data is sent in the message body.
24.07.23 Mondragon Unibertsitatea 48
Receiving data in different formats
• In this example, the addStudentJSON method receives and
returns a student object in JSON format.
24.07.23 Mondragon Unibertsitatea 49
Receiving data in different formats
• Testing the service sending data in the message body (example
with JSON):
In the request body we
We include JSON data inside select raw->JSON to indicate
the message request that the request body will
include JSON data
24.07.23 Mondragon Unibertsitatea 50
Exercise
• Test the addStudentJSON method.
• Test addStudentXML method that receives and returns the
information about the student in XML format.
• Test them with Postman.
24.07.23 Mondragon Unibertsitatea 51
Produce/receive in several formats
• To produce and receive data in several formats in the same
REST method we list the formats in the produces or consumes
annotation:
• When testing the service with Postman, we must indicate the
data format in which we want to receive the information:
24.07.23 Mondragon Unibertsitatea 52
Exercise
• Test POST method named addStudent.
• The method receives and returns a student object in both XML
and JSON formats
• Test it in Postman making two requests:
• POST request sending and receiving JSON data.
• POST request sending and receiving XML data.
24.07.23 Mondragon Unibertsitatea 53
HTTP
4 Response
Management
Managing Responses
• As we have seen, the @ResponseEntity annotation is used to
manage the REST responses and the data they contain.
• We can specify the response status, header and body.
Status
Body
Header
• It is not mandatory to include all the response parameters (i.e., we
can include only the response status).
24.07.23 Mondragon Unibertsitatea 55
Managing Responses
• We can include objects (or arrays) in the response (along with the
status).
OK: 200
• Other status examples:
• HttpStatus.NOT_FOUND: status 404 (Not found)
• HttpStatus.CREATED: status 201 (Created)
24.07.23 Mondragon Unibertsitatea 56
Managing Responses
• We can also build the response only with the status (without
including any content).
OK: 200
Not found: 404
• In these cases the method is of ResponseEntity type:
Public ResponseEnitity<String> sampleMethod()
You can find the different HTTP status codes at
https://docs.spring.io/spring-framework/docs/current/javadoc-
api/org/springframework/http/HttpStatus.html
24.07.23 Mondragon Unibertsitatea 57
5
Summary
Spring REST annotations
Annotation Description
@RestController Indicates that the class is a REST service
Used to map web requests to Spring Controller
@RequestMapping
methods
Maps HTTP GET requests onto specific handler
@GetMapping
methods.
Maps HTTP POST requests onto specific handler
@PostMapping
methods.
Maps HTTP PUT requests onto specific handler
@PutMapping
methods.
Maps HTTP DELETE requests onto specific handler
@DeleteMapping
methods.
24.07.23 Mondragon Unibertsitatea 59
Spring REST annotations
Annotation Description
Used to handle template variables in the request URI
@PathVariable
mapping, and set them as method parameters
Used to extract query parameters, form parameters,
@RequestParam
and even files from the request
Used to enable class object transformation (from the
@Data
a REST method poing of view)
To specify the value of an annotation (for example the
value
path of a get method inside @GetMapping).
To specify the data type returned by a REST method
produces
(i.e., application/xml, application/json, etc.)
To specify the data type consumed by a REST method
consumes
(i.e., application/xml, application/json, etc.)
24.07.23 Mondragon Unibertsitatea 60
6 Examples and
interesting lins
Examples in Mudle
1. REST_HelloWorld
Sample REST service that we have implemented in this tutorial
2. REST_Calculator
Service with methods that perform basic calculations
3. REST_CRUD_Example
Service that includes GET, POST, PUT and DELETE operations to
manage data about a set of articles.
4. REST_CRUD_DB_Example (we will see in the next days)
The same as CRUD example but in this case the information about
articles is stored in a database.
24.07.23 Mondragon Unibertsitatea 62
Examples in Mudle
1. REST_HelloWorld
Sample REST service that we have implemented in this tutorial
2. REST_Calculator
Service with methods that perform basic calculations
3. REST_CRUD_Example
Service that includes GET, POST, PUT and DELETE operations to
manage data about a set of articles.
4. REST_CRUD_DB_Example (we will see in the next days)
The same as CRUD example but in this case the information about
articles is stored in a database.
24.07.23 Mondragon Unibertsitatea 63
Interesting links
Building REST services in Spring
https://spring.io/guides/tutorials/rest/
Building a RESTful Web service
https://spring.io/guides/gs/rest-service/
Main annotations of Spring used to develop REST services
https://www.java67.com/2019/04/top-10-spring-mvc-and-rest-
annotations-examples-java.html
24.07.23 Mondragon Unibertsitatea 64
Interesting links
Spring Response entity tutorial:
https://www.baeldung.com/spring-response-entity
Consuming and producing data in JSON
https://www.baeldung.com/spring-boot-json
Tutorial to use Spring + REST + XML:
https://www.geeksforgeeks.org/spring-rest-xml-response/
24.07.23 Mondragon Unibertsitatea 65
Exercise
• Create the Postman requests to test the REST_CRUD_Example
service methods.
• You have to submit to Mudle the Postman collection that contains
all the requests.
24.07.23 Mondragon Unibertsitatea 66
Exercise
• Steps export a postman collection (in .json format):
24.07.23 Mondragon Unibertsitatea 67
Creation of
REST services
with Spring
Javier Cuenca
[email protected]