项目作者: AntonioDiaz

项目描述 :
Spring REST training
高级语言: Java
项目地址: git://github.com/AntonioDiaz/spring_rest.git
创建时间: 2019-02-26T13:34:38Z
项目社区:https://github.com/AntonioDiaz/spring_rest

开源协议:

下载


Spring REST training

HTTP

Messages

  • Request
    • URL
      • Address of the resource
      • Optional parameters
    • Method: POST, PUT, DELETE, GET, …
    • Headers
      • Accept (content type)
      • Authentication
    • Body (for PUT and POST operations)
  • Response
    • Status Code
    • Headers: content type, date, …
    • Body (for most request)

      Verbs

Verb Action Should be Idempotent
(always same result)
Should be safe
(don’t change resources)
GET fetch
an existing resource
yes yes
POST create
a new resource
no no
PUT update
an existing resource
yes no
DELETE delete
an existing resource
yes no
HEAD fetch headers of
an existing resource
yes yes
OPTIONS fetch methods of
an existing resource
yes yes
PATCH modify
an existing resource
no no

Status

https://www.restapitutorial.com/httpstatuscodes.html

Important concepts

https://start.spring.io/ → create spring boot project from scratch.

Create custom Exceptions

Swagger (now Open Api)

  • Add dependencies to pom.xml
  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-swagger2</artifactId>
  4. <version>2.4.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.springfox</groupId>
  8. <artifactId>springfox-swagger-ui</artifactId>
  9. <version>2.4.0</version>
  10. </dependency>
  • Add config class
  1. package com.adiaz;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import springfox.documentation.service.ApiInfo;
  5. import springfox.documentation.service.Contact;
  6. import springfox.documentation.spi.DocumentationType;
  7. import springfox.documentation.spring.web.plugins.Docket;
  8. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  9. @Configuration
  10. @EnableSwagger2
  11. public class SwaggerConfig {
  12. private static final Contact CONTACT = new Contact ("a_name", "http://www.contact_url.org", "contact@email.com");
  13. private static final ApiInfo MY_API_INFO = new ApiInfo("My awesonme API Documentation",
  14. "This is an getting started proof of concept API", "1.0.1",
  15. "https://en.wikipedia.org/wiki/MIT_License",
  16. CONTACT, "MIT", "https://opensource.org/licenses/MIT");
  17. @Bean
  18. public Docket api() {
  19. return new Docket(DocumentationType.SWAGGER_2).apiInfo(MY_API_INFO);
  20. }
  21. }

Persitence

  1. Add dependencies JPA and H2
    • JPA: persistence standard for Java.
    • H2: database in memory for development purpose.
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>com.h2database</groupId>
  7. <artifactId>h2</artifactId>
  8. <scope>runtime</scope>
  9. </dependency>
  1. Add annotations:
  1. H2 console:
    http://localhost:8080/h2-console
    Default database name: jdbc:h2:mem:testdb

Working with APIs

  • Swagger
  • RAML
  • API BluePrint
  • OpenAPI 2 (Swagger2)
  • Swagger Tools

    • Swagger Editor
    • Swagger UI
    • Swagger Codegen
  • YAML: http://www.yamllint.com/

https://editor.swagger.io

Testing

http://dredd.org

  1. Generate yaml with swagger Editor (https://editor.swagger.io/)
  2. Save locally
  3. Start server
  4. Call dredd to test

    dreed api-description-hellobean.yml http://localhost:8080

  1. swagger: "2.0"
  2. info:
  3. version: "1.0"
  4. title: "Example API"
  5. basePath: /
  6. schemes:
  7. - http
  8. paths:
  9. /helloBean:
  10. get:
  11. produces:
  12. - application/json;charset=utf-8
  13. responses:
  14. '200':
  15. description: 'OK'
  16. schema:
  17. type: object
  18. properties:
  19. message:
  20. type: string
  21. required:
  22. - message
  • CodeFirst
  • Contract or API or design FIRST

Generate Code with Swagger2

  • From Swagger Editor generate server, select spring
  • Extract zip
  • Import project as: “Existing maven project”

HATEOAS

Add links with resources to response.
Example:

  1. {
  2. "id": 2,
  3. "name": "antonio",
  4. "birthDate": "2019-02-27T14:20:22.994+0000",
  5. "_links": {
  6. "all-users": {
  7. "href": "http://localhost:8080/users"
  8. }
  9. }
  10. }
  1. Add library to pom.xml.
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-hateoas</artifactId>
  4. </dependency>
  1. Add code to Controller
  1. @GetMapping("/users/{id}")
  2. public Resource<User> usersRetrieve(@PathVariable int id) throws UserNotFoundException {
  3. User user = serviceUser.findUser(id);
  4. if (user==null) {
  5. throw new UserNotFoundException("No existe listillo");
  6. }
  7. Resource<User> resource = new Resource<>(user);
  8. ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).usersRetrieve());
  9. resource.add(linkTo.withRel("all-users"));
  10. return resource;
  11. }