Git Product home page Git Product logo

art-sfg-spring5-mvc-rest's Introduction

CircleCI codecov

art-sfg-spring5-mvc-rest

SFG Tutorial Spring 5 - Section 24 Restful WebServices with Spring MVC

We are cloning https://api.predic8.de/shop/docs#!/

Introduction to Swagger Editor (403)

  1. visit editor.swagger.io
  2. copy from json code from your project localhost:8080/v2/api-docs
  3. paste it in editor.swagger.io, modify

Swagger Code Generator (404)

  1. go to swagger editor site
  2. Generate Server
  3. download code to review skeleton

Spring MVC Content Negotiation Overview (427)

  1. ContentNegotiatingViewResolver
  2. View
  3. MappingJackson2JsonView

art-sfg-spring5-mvc-rest's People

Contributors

artshishkin avatar

Watchers

 avatar

art-sfg-spring5-mvc-rest's Issues

Customizing Swagger with Meta Data (399)

  1. Look at class ApiInfo.class, Contact.java
  2. in config class add method to create ApiInfo:
    • private ApiInfo metaData()
    • create Contact
    • create ApiInfo
  3. add apiInfo to the Docket bean

Externalize API URL Value (389)

  1. @RequestMapping(CategoryController.BASE_URL)
  2. same with CustomerController
  3. in CustomerServiceImpl create method getCustomerUrl(id)
  4. in tests use BASE url

Create Vendors API -Assignment (392)

  1. implement Fruit Shop Vendors API
  2. develop all backend code:
    • domain
    • repository
    • service
    • dto
    • type converter
  3. use TDD
  4. create Controller to support
    • GET, POST, DELETE, GET BY ID, PATCH, PUT
  5. skip Product API Calls

Update Customer Controller part (387)

  1. TDD:
    • create test testPatchCustomer with perform patch
  2. create endpoint using ResponseEntity<> (just for study cases)
  3. make sure customer_url is valid

Configure swagger (397)

  1. add dependencies
    • springfox-swagger2
    • springfox-swagger-ui
  2. create configuration class config.SwaggerConfig and @EnableSwagger2
  3. go to /v2/api-docs to see full documentation
  4. configure documentation
    • in swagger config create bean of type Docker - new Docket(...SWAGGER2)
    • then .select().apis(...any())
    • then .paths(...any())
    • .build()
    • .pathMapping("/");

Exception Handling (390)

Try with EntityNotFoundException first

  1. new ResourceNotFoundException class extends RuntimeException
  2. in tests - 404
  3. @ControllerAdvice class RestResponseEntityExceptionHandler
    • extends ResponseEntityExceptionHandler
    • @ExceptionHandler()
    • method returns new ResponseEntity<Object>("Resource Not Found", new HttpHeaders(), NOT_FOUND);
  4. in services return our ResourceNotFoundException

New Spring Boot Project (374)

  1. visit https://api.predic8.de/shop/docs#!/ - we are going to build something like this
  2. create Spring Boot project
    • web, devtools, h2, lombok
    • JacoCo
  3. domain.Category (Long id (identity), name)
  4. repositories.CategoryRepository - JpaRepo
  5. api.v1.model.CategoryDTO (id, name)
  6. create CircleCI configuration
  7. add CodeCov configuration

Customize Vendors: Assignment (401)

  • use @Api to update description of API Endpoint
  • use @ApiOperation to update description of API Operations
  • use @ApiModelProperties to update description of model properties

Update Customer using PATCH, Integration Test with DataJpaTest (386)

  1. in service create method patchCustomer(id,dto)
    • find customer by id
    • if not found throw EntityNotFound
    • if dto.field not null update customer.field
    • save
  2. create CustomerServiceImplIT test
    • autowire necessary repositories
    • new BootStrapClass().run()
    • new CustomerServiceImpl()
    • test case patchCustomerUpdateFirstName()
    • test case patchCustomerUpdateLastName()

Using MapStruct (377)

  1. add dependency
  2. set up maven-compiler plugin
    • set annotation processors paths for lombok and mapstruct
    • set up compiler arg -Amapstruct.defaultComponentModelspring
  3. create api.v1.mapper.CategoryMapper
    • categryToCategoryDto
  4. create unit test for mapper

List Categories (380)

  1. create controllers.v1.CategoryController
  2. base endpoint is /api/v1/categories
    • getAlCategries
    • getByName
  3. CategoryListDTO wrapper of List - to match Sample Project from https://api.predic8.de/shop/docs#!/
  4. mockMvc test
    • John uses .andExpect(jsonPath("$.categories", hasSize(2)))
    • John uses .andExpect(jsonPath("$.name", equalTo(NAME)))

Introduction to XML Schema (428)

  1. generate XSD (xml-schema):
    • copy xml-response of all customers endpoint
    • use xsd-generator (like this)
  2. try different options (choose third - like in our project)
  3. in root folder of project create folder rest-model - like module in multi-module project
  4. create file /rest-model/src/main/resources/xsd/customer.xsd

Refactor for JAXB Generated Classes (431)

  1. in xsd change name of class Customer to CustomerDTO
  2. remove CustomerDTO from api.v1.model
  3. change constructor call if needed
  4. if circle ci fails then add:
    • - run: mvn install -Dskiptests
    • - run: mvn dependency:go-offline

Category Service (379)

  1. services.CategoryService - interface
    • List<CategoryDTO> getAllCategories()
    • getCategoryByName
  2. implementation
  3. junit tests with mapper

Create New Customer Endpoint (384)

  1. do not forget to set customerUrl in service
  2. modify tests:
    • CustomerServiceImplTest - assertThat customerUrl is valid
    • create AbstractRestControllerTest - with method static String asJsonString(final Object obj)
    • in test mockMvc... content(asJsonString(customerDto))
  3. TDD: then create Endpoint
  4. add trailing slash support

Delete Customer (388)

  1. in service create method deleteCustomerById(id)
    • find customer by id
    • if absent - throw an Exception
    • delete it and return void
  2. service test
    • delete
    • make sure repo call method to delete
  3. TDD:
    • test for controller
    • THEN controller endpoint

Swagger UI (398)

  1. go to localhost:8080/swagger-ui.html to see UI
  2. if you do not see UI, change config (NOT IN SPRING BOOT):
    • SwaggerConfig extends WebMvcConfigurationSupport
    • override addResourceHandlers(... registry)
    • registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    • registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

Customizing Endpoint Documentation (400)

  1. customize CustomerController
    • annotate controller with @Api(description="BlaBla")
    • endpoint with @ApiOperation(value="This will get list of customers.", notes="There are some notes about the API.")
  2. customize model CustomerDTO
    • annotate property with @ApiModelProperty(value="This is the first name", required=true)

Using Multi-Module Maven Builds with Spring Boot (429)

  1. refactor to have 2 modules:
    • rest-model
    • spring5-mvc-rest-app
  2. changes in root pom.xml
    • artifactId --> ...-mvc-rest-parent
    • packaging --> pom
    • added section modules
    • dependencies and plugins moved to child pom
  3. rest-model pom
    • simple
    • name is spring5-mvc-model
  4. art-sfg-spring5-rest-app
    • all the code from previous

Using JAXB to Generate Java Classes (430)

  1. use jaxb2-maven-plugin
    • packageName is com.artarkatesoft.model
    • configure sources folder as src/main/resources/xsd
  2. clean, package model module
  3. look at generated java classes
  4. change customer.xsd to have classes we want
    • type CustomerListDTOType --> CustomerListDTO
    • type customersType --> Customer
    • customer_url --> customerUrl
    • move element of type Customer named customers from Customer to CustomerListDTO

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.