Training - REST & Spring Boot

Last Updated on: August 11, 2021 pm

REST & Spring Boot

Spring Enterprise Web Architecture

REST

Introducing REST

REST stands for Representational State Transfer

REST is a style of architecture

  • The Web is a large set of resources
  • As a client selects a resource, they are then in a particular state
  • The client can then select a different resource, and be in a different state as they now have a different resource

Resources

A resource always has a simple URL

At the end of the URL will be URLs for other resources allowing you to get more information (and therefore change state)

URLs are logical names for resources.

The actual location should be resolved by technology on the server

  • Such as a Spring MVC Controller

REST and Web Services

  • Clients send HTTP requests using the four HTTP methods
  • Simple parameters can be passed in the URL
  • Complex parameters are passed in the header as XML or JSON

The Richardson Maturity Model

For more information

Spring RESTful Service

Controller

GET All Person

1
2
3
4
5
@RequestMapping(method = RequestMethod.GET)
//@GetMapping
public Collection<Person> getPeople() {
return people.values();
}

Controller methods are annotated using @RequestMapping to specify

  • Which URL (in this case /people as this was placed on the whole class)
  • Which HTTP method (in this case GET)

Find Person by Id

Use @PathVariable

1
2
3
4
@GetMapping(value="/{id}")
public Person getPersonById(@PathVariable("id") int id) {
return people.get(id);
}

http://localhost:8080/people/3

Query String Parameters

1
2
3
public Person getPersonById(@RequestParam("id") int id){
return people.get(id);
}

http://localhost:8080/people?id=3

Create a Person

@PostMapping(consumes=”..”)

@PostMapping(consumes="application/json", produce="application/json")

  • The consumes attribute specifies the data type of the data being submitted, defaulting to application/json
  • The produce attribute specifies the MIME type of the return value in our case, defaulting to application/json

@RequestBody

1
2
public void addPerson(@RequestBody Person p) {
}

The @RequestBody attribute means that the JSON submitted will be automatically marshalled into a Person object

How to Return a 404

Use a ResponseEntity return type, and set its status

1
2
3
4
5
6
7
8
9
@RequestMapping(value="/with404/{id}", method=RequestMethod.GET)
public ResponseEntity<Person> getPersonByIdHandling404(@PathVariable("id") int id) {
Person personToReturn = people.get(id); if (personToReturn ==null) {
return new ResponseEntity<Person>(HttpStatus.NOT_FOUND);
}
else {
return new ResponseEntity<Person>(personToReturn, HttpStatus.OK);
}
}

Spring Java Configuration

1
2
3
4
5
6
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com....")
public class AppConfig extends WebMvcConfigurerAdapter{

}

The WebMvcConfigurerAdapter class provides methods that can be overridden to change specific Web settings such as resource folder locations

Override the addResourcesHandlers method

1
2
3
4
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}

Loading Config Class

AbstractAnnotationConfigDispatcherServletInitializer

  • Extend the abstract base class
  • Override some required methods
  • Specify servlet mapping and location of your app config
1
2
3
4
5
6
7
8
9
10
11
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
protected Class<?>[] getServletConfigClasses() {
return null;
}
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

CORS Configuration

Cross Origin Resource Sharing (CORS) allows you to configure whether web pages from sites other than your own can invoke your REST API

By default, browsers will prevent Web sites calling REST APIs on other servers unless the server specifically allows it

  • Allow it is achieved by a header set on the server

Enabling CORS in Spring

Annotate the request methods for REST Controller - @CrossOrigin

1
2
@CrossOrigin 
@RestController

Open API/Swagger

Open API

Open API is a Specification format for REST APIs. An OpenAPI file includes:

  • Available Endpoints and operations to each endpoint.
  • Operation parameters for both input and output.
  • Authentication methods.
  • Contact information/license/terms of conditions.

Swagger

Swagger is a set of tools built around OpenAPI Specification.

  • Swagger UI - renders OpenAPI specs without having any implementation logic.
  • Swagger Editor - browser-based editor where you can write OpenAPI specs.

Add Dependency and Annotation

1
2
3
4
5
6
7
8
9
10
11
12
 <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<scope>compile</scope>
</dependency>
SwaggerConfig File

Enables @EnablesSwagger2 in SwaggerConfig.java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@EnableSwagger2
@Profile("!test")
public class SwaggerConfig {

@Bean
public Docket newsApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("compactdiscs")
.apiInfo(apiInfo())
// 指定构建api文档的详细信息的方法为:apiInfo()
.select()
.paths(PathSelectors.any())
// 根据urls设置需要加入文档的请求和需要忽略的请求
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Album REST API with Swagger and SpringBoot")
.description("This API allows you to interact with albums. It is a CRUD API")
.contact(new Contact("FirstName LastName", "http://www.google.com", "xxx@gmail.com"))
//.version("2.0")
.build();
}
}
Add Annotations to AppConfig.java and Controllers

Enables @Import(SwaggerConfig.class) in AppConfig.java.

1
2
3
4
5
6
7
8
@EnableAutoConfiguration
@ComponentScan
@Import(SwaggerConfig.class)
public class AppConfig {
public static void main(String[] args) {
SpringApplication.run(AppConfig.class, args);
}
}

More annotations like @ApiOperation can be placed in the controller.

1
2
@ApiOperation(value = "findAll", nickname = "findAll")
@GetMethod
Swagger URL

http://localhost:8080/swagger-ui.html#/