REST microservice that does currency conversion using https://currencyapi.com/. Basic template forked from spring-guides.
This guide walks you through the process of creating a “Hello, World” RESTful web service with Spring that includes headers for Cross-Origin Resource Sharing (CORS) in the response. You can find more information about Spring CORS support in this blog post.
== What You Will Build
You will build a service that accepts HTTP GET requests at
http://localhost:8080/greeting
and responds with a JSON representation of a greeting, as the following listing shows:{"id":1,"content":"Hello, World!"}You can customize the greeting with an optional
name
parameter in the query string, as the following listing shows:http://localhost:8080/greeting?name=User
The
name
parameter value overrides the default value ofWorld
and is reflected in the response, as the following listing shows:{"id":1,"content":"Hello, User!"}This service differs slightly from the one described in Building a RESTful Web Service, in that it uses Spring Framework CORS support to add the relevant CORS response headers.
== What You Need
== Starting with Spring Initializr
You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
Click Dependencies and select Spring Web.
Click Generate.
Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
NoteIf your IDE has the Spring Initializr integration, you can complete this process from your IDE.
NoteYou can also fork the project from Github and open it in your IDE or other editor. === Adding the
httpclient
DependencyThe tests (in
complete/src/test/java/com/example/restservicecors/GreetingIntegrationTests.java
) require the Apachehttpclient
library.To add the Apache
httpclient
library to Maven, add the following dependency:<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <scope>test</scope> </dependency>The following listing shows the finished
pom.xml
file:link:complete/pom.xml[role=include]To add the Apache
httpclient
library to Gradle, add the following dependency:testImplementation 'org.apache.httpcomponents:httpclient'
The following listing shows the finished
build.gradle
file:link:complete/build.gradle[role=include]== Create a Resource Representation Class
Now that you have set up the project and build system, you can create your web service.
Begin the process by thinking about service interactions.
The service will handle
GET
requests to/greeting
, optionally with aname
parameter in the query string. TheGET
request should return a200 OK
response with JSON in the body to represent a greeting. It should resemble the following listing:{ "id": 1, "content": "Hello, World!" }The
id
field is a unique identifier for the greeting, andcontent
is the textual representation of the greeting.To model the greeting representation, create a resource representation class. Provide a plain old Java object with fields, constructors, and accessors for the
id
andcontent
data, as the following listing (fromsrc/main/java/com/example/restservicecors/Greeting.java
) shows:link:complete/src/main/java/com/example/restservicecors/Greeting.java[role=include]
NoteSpring uses the Jackson JSON library to automatically marshal instances of type Greeting
into JSON.== Create a Resource Controller
In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the
@Controller
annotation, and theGreetingController
shown in the following listing (fromsrc/main/java/com/example/restservicecors/GreetingController.java
) handlesGET
requests for/greeting
by returning a new instance of theGreeting
class:link:complete/src/main/java/com/example/restservicecors/GreetingController.java[role=include]This controller is concise and simple, but there is plenty going on under the hood. We break it down step by step.
The
@RequestMapping
annotation ensures that HTTP requests to/greeting
are mapped to thegreeting()
method.
NoteThe preceding example uses the @GetMapping
annotation, which acts as a shortcut for@RequestMapping(method = RequestMethod.GET)
. We useGET
in this case because it is convenient for testing. Spring will still reject a GET request where the origin doesn’t match the CORS configuration. The browser is not required to send a CORS preflight request, but we could use@PostMapping
and accept some JSON in the body if we wanted to trigger a pre-flight check.
@RequestParam
binds the value of thename
query string parameter into thename
parameter of thegreeting()
method. This query string parameter is notrequired
. If it is absent in the request, thedefaultValue
ofWorld
is used.The implementation of the method body creates and returns a new
Greeting
object, with the value of theid
attribute based on the next value from thecounter
and the value of thecontent
based on the query parameter or the default value. It also formats the givenname
by using the greetingtemplate
.A key difference between a traditional MVC controller and the RESTful web service controller shown earlier is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller populates and returns a
Greeting
object. The object data is written directly to the HTTP response as JSON.To accomplish this, the {RestController}[
@RestController
] annotation assumes that every method inherits the@ResponseBody
semantics by default. Therefore, a returned object data is inserted directly into the response body.Thanks to Spring’s HTTP message converter support, the
Greeting
object is naturally converted to JSON. Because Jackson is on the classpath, Spring’sMappingJackson2HttpMessageConverter
is automatically chosen to convert theGreeting
instance to JSON.== Enabling CORS
You can enable cross-origin resource sharing (CORS) from either in individual controllers or globally. The following topics describe how to do so:
=== Controller Method CORS Configuration
So that the RESTful web service will include CORS access control headers in its response, you have to add a
@CrossOrigin
annotation to the handler method, as the following listing (fromsrc/main/java/com/example/restservicecors/GreetingController.java
) shows:link:complete/src/main/java/com/example/restservicecors/GreetingController.java[role=include]This
@CrossOrigin
annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the@RequestMapping
annotation. Also, amaxAge
of 30 minutes is used. You can customize this behavior by specifying the value of one of the following annotation attributes:
origins
methods
allowedHeaders
exposedHeaders
allowCredentials
maxAge
.In this example, we allow only
http://localhost:8080
to send cross-origin requests.
NoteYou can also add the @CrossOrigin
annotation at the controller class level as well, to enable CORS on all handler methods of this class.=== Global CORS configuration
In addition (or as an alternative) to fine-grained annotation-based configuration, you can define some global CORS configuration as well. This is similar to using a
Filter
but can be declared within Spring MVC and combined with fine-grained@CrossOrigin
configuration. By default, all origins andGET
,HEAD
, andPOST
methods are allowed.The following listing (from
src/main/java/com/example/restservicecors/GreetingController.java
) shows thegreetingWithJavaconfig
method in theGreetingController
class:link:complete/src/main/java/com/example/restservicecors/GreetingController.java[role=include]
NoteThe difference between the greetingWithJavaconfig
method and thegreeting
method (used in the controller-level CORS configuration) is the route (/greeting-javaconfig
rather than/greeting
) and the presence of the@CrossOrigin
origin.The following listing (from
src/main/java/com/example/restservicecors/RestServiceCorsApplication.java
) shows how to add CORS mapping in the application class:link:complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[role=include]You can easily change any properties (such as
allowedOrigins
in the example), as well as apply this CORS configuration to a specific path pattern.
TipYou can combine global- and controller-level CORS configuration. == Creating the Application Class
The Spring Initializr creates a bare-bones application class for you. The following listing (from
initial/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java
) shows that initial class:link:initial/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[role=include]You need to add a method to configure how to handle cross-origin resource sharing. The following listing (from
complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java
) shows how to do so:link:complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[role=include]The following listing shows the completed application class:
link:complete/src/main/java/com/example/restservicecors/RestServiceCorsApplication.java[role=include]Logging output is displayed. The service should be up and running within a few seconds.
== Test the service
Now that the service is up, visit
http://localhost:8080/greeting
in your browser where you should see:{"id":1,"content":"Hello, World!"}Provide a
name
query string parameter by visitinghttp://localhost:8080/greeting?name=User
. The value of thecontent
attribute changes fromHello, World!
toHello User!
, as the following listing shows:{"id":2,"content":"Hello, User!"}This change demonstrates that the
@RequestParam
arrangement inGreetingController
works as expected. Thename
parameter has been given a default value ofWorld
but can always be explicitly overridden through the query string.Also, the
id
attribute has changed from1
to2
. This proves that you are working against the sameGreetingController
instance across multiple requests and that itscounter
field is being incremented on each call, as expected.Now you can test that the CORS headers are in place and allow a Javascript client from another origin to access the service. To do so, you need to create a Javascript client to consume the service. The following listing shows such a client:
First, create a simple Javascript file named
hello.js
(fromcomplete/public/hello.js
) with the following content:link:complete/public/hello.js[role=include]This script uses jQuery to consume the REST service at
http://localhost:8080/greeting
. It is loaded byindex.html
, as the following listing (fromcomplete/public/index.html
) shows:link:complete/public/index.html[role=include]
NoteThis is essentially the REST client created in Consuming a RESTful Web Service with jQuery, modified slightly to consume the service when it runs on localhost at port 8080. See that guide for more details on how this client was developed. To start the client running on localhost at port 8080, run the following Maven command:
./mvnw spring-boot:runIf you use Gradle, you can use this command:
./gradlew bootRun
Once the app starts, open http://localhost:8080 in your browser, where you should see the following:
To test the CORS behaviour, you need to start the client from another server or port. Doing so not only avoids a collision between the two applications but also ensures that the client code is served from a different origin than the service. To start the app running on localhost at port 9000 (as well as the one that is already running on port 8080), run the following Maven command:
./mvnw spring-boot:run -Dserver.port=9000If you use Gradle, you can use this command:
./gradlew bootRun --args="--server.port=9000"
Once the app starts, open http://localhost:9000 in your browser, where you should see the following:
If the service response includes the CORS headers, then the ID and content are rendered into the page. But if the CORS headers are missing (or insufficient for the client), the browser fails the request and the values are not rendered into the DOM.
== Summary
Congratulations! You have just developed a RESTful web service that includes Cross-Origin Resource Sharing with Spring.
== See Also
The following guides may also be helpful: