Slide 1

Slide 1 text

A Test-Driven Approach to Documenting RESTful APIs with Groovy and Spring REST Docs Jenn Strater @codeJENNerator

Slide 2

Slide 2 text

@codeJENNerator Note For Those Viewing Slides Online • Bulleted text like this indicates the key points mentioned on a previous slide. They may not have been included in the official presentation. • If this view does not support links, the links will work in the pdf. Click the ‘download pdf’ button on the right.

Slide 3

Slide 3 text

@codeJENNerator https://speakerdeck.com/jlstrater/test-driven-docs-cekrakow-2017 https://github.com/jlstrater/groovy-spring-boot-restdocs-example https://github.com/ratpack/example-books https://github.com/jlstrater/spring-restdocs-public-api-example Follow Along

Slide 4

Slide 4 text

@codeJENNerator About Me

Slide 5

Slide 5 text

@codeJENNerator About Me Starting at Zenjob in Berlin in June 2017!

Slide 6

Slide 6 text

@codeJENNerator About Me - Taking classes at the Technical University of Denmark and working on a research project - Also exploring Danish Culture with funding from the US Fulbright Grant program - Prior to the Fulbright Grant, I was a senior consultant at Object Partners, Inc. in Minneapolis, MN, USA. My work there is the subject of this talk. - Co-founder of Gr8Ladies and talk about women in the Groovy Community all over the world - Passionate about bring new people into the Groovy community through free introductory workshops called Gr8Workshops. - Moving to Berlin and starting at Zenjob in June 2017.

Slide 7

Slide 7 text

@codeJENNerator Background

Slide 8

Slide 8 text

@codeJENNerator Background • Creating RESTful APIs • Spring Boot • Ratpack • Grails

Slide 9

Slide 9 text

@codeJENNerator Background • Creating RESTful APIs • Spring Boot • Ratpack • Grails • Documentation • Swagger • Asciidoctor

Slide 10

Slide 10 text

@codeJENNerator img src: https://flic.kr/p/rehEf5

Slide 11

Slide 11 text

@codeJENNerator I hate writing documentation!* img src: https://flic.kr/p/rehEf5

Slide 12

Slide 12 text

@codeJENNerator Example Case

Slide 13

Slide 13 text

@codeJENNerator Factors in Choosing a Documentation Solution

Slide 14

Slide 14 text

@codeJENNerator REST Maturity Model img src: http://martinfowler.com/articles/richardsonMaturityModel.html

Slide 15

Slide 15 text

@codeJENNerator REST Maturity Model img src: http://martinfowler.com/articles/richardsonMaturityModel.html

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

@codeJENNerator Central Information Security Http Verbs Error Handling Http Status

Slide 18

Slide 18 text

@codeJENNerator Endpoint Vs Resource Design

Slide 19

Slide 19 text

@codeJENNerator Endpoint Vs Resource Design VS

Slide 20

Slide 20 text

@codeJENNerator Swagger

Slide 21

Slide 21 text

@codeJENNerator Swagger Approaches

Slide 22

Slide 22 text

@codeJENNerator SpringFox img src: https://www.flickr.com/photos/24874528@N04/17125924230

Slide 23

Slide 23 text

@codeJENNerator Super Easy Install • io.springfox:springfox-swagger2 • io.springfox:springfox-swagger-ui

Slide 24

Slide 24 text

@codeJENNerator Custom Swagger Specification

Slide 25

Slide 25 text

@codeJENNerator Custom JSON {
 "swagger": "2.0",
 "info": {
 "version": "1",
 "title": "My Service",
 "contact": {
 "name": "Company Name"
 },
 "license": {}
 },
 "host": "example.com",
 "basepath": "/docs",
 "tags": [
 {
 "name": "group name",
 "description": "what this group of api endpoints is for",
 }
 ],
 "paths": {
 "/api/v1/groupname/resource":
 .
 .
 .
 }

Slide 26

Slide 26 text

@codeJENNerator Swagger UI • Springfox generated UI • Copy static files and customize

Slide 27

Slide 27 text

@codeJENNerator Considerations

Slide 28

Slide 28 text

@codeJENNerator Customization img src: http://sergiodelamo.es/how-to-secure-your-grails-3-api-with-spring-security-rest-for-grails/

Slide 29

Slide 29 text

@codeJENNerator 1 @Secured(‘ROLE_ALLOWED_TO_PERFORM_ACTION’)
 2 @RequestMapping(value = '/v1/serviceName/actionName', method = 3 RequestMethod.POST)
 4 @ApiOperation(value = '/actionName',
 5 notes = 'Enables or disables setting via "1" or "0", respectively')
 6 @ApiResponses(value = [
 7 @ApiResponse(code = 200, response = CustomSettingResponse, message = 8 ‘Successful setting update'),
 9 @ApiResponse(code = 400, response = ErrorResponse, message = 'Invalid 10 user input'),
 11 @ApiResponse(code = 500, response = ErrorResponse, message = 'Unexpected 12 server error')
 13 ])
 14 CustomSettingResponse setSetting(@RequestBody CustomModel settingsValue) {
 15 SaveSettingUpdateRequest request = new SaveSettingUpdateRequest (
 16 settingsValue.fieldOne,
 17 [new TransformedSetting(SettingEnum.POSSIBLE_ENUM_VALUE, 18 new Double(settingsValue.value))]
 19 )
 20 api.saveUpdatedSetting(request)
 21 }

Slide 30

Slide 30 text

@codeJENNerator Annotation Hell 1 @Secured(‘ROLE_ALLOWED_TO_PERFORM_ACTION’)
 2 @RequestMapping(value = '/v1/serviceName/actionName', method = 3 RequestMethod.POST)
 4 @ApiOperation(value = '/actionName',
 5 notes = 'Enables or disables setting via "1" or "0", respectively')
 6 @ApiResponses(value = [
 7 @ApiResponse(code = 200, response = CustomSettingResponse, message = 8 ‘Successful setting update'),
 9 @ApiResponse(code = 400, response = ErrorResponse, message = 'Invalid 10 user input'),
 11 @ApiResponse(code = 500, response = ErrorResponse, message = 'Unexpected 12 server error')
 13 ])
 14 CustomSettingResponse setSetting(@RequestBody CustomModel settingsValue) {
 15 SaveSettingUpdateRequest request = new SaveSettingUpdateRequest (
 16 settingsValue.fieldOne,
 17 [new TransformedSetting(SettingEnum.POSSIBLE_ENUM_VALUE, 18 new Double(settingsValue.value))]
 19 )
 20 api.saveUpdatedSetting(request)
 21 }

Slide 31

Slide 31 text

@codeJENNerator Annotation Hell 1 @Secured(‘ROLE_ALLOWED_TO_PERFORM_ACTION’)
 2 @RequestMapping(value = '/v1/serviceName/actionName', method = 3 RequestMethod.POST)
 4 @ApiOperation(value = '/actionName',
 5 notes = 'Enables or disables setting via "1" or "0", respectively')
 6 @ApiResponses(value = [
 7 @ApiResponse(code = 200, response = CustomSettingResponse, message = 8 ‘Successful setting update'),
 9 @ApiResponse(code = 400, response = ErrorResponse, message = 'Invalid 10 user input'),
 11 @ApiResponse(code = 500, response = ErrorResponse, message = 'Unexpected 12 server error')
 13 ])
 14 CustomSettingResponse setSetting(@RequestBody CustomModel settingsValue) {
 15 SaveSettingUpdateRequest request = new SaveSettingUpdateRequest (
 16 settingsValue.fieldOne,
 17 [new TransformedSetting(SettingEnum.POSSIBLE_ENUM_VALUE, 18 new Double(settingsValue.value))]
 19 )
 20 api.saveUpdatedSetting(request)
 21 }

Slide 32

Slide 32 text

@codeJENNerator Annotation Hell 1 @Secured(‘ROLE_ALLOWED_TO_PERFORM_ACTION’)
 2 @RequestMapping(value = '/v1/serviceName/actionName', method = 3 RequestMethod.POST)
 4 @ApiOperation(value = '/actionName',
 5 notes = 'Enables or disables setting via "1" or "0", respectively')
 6 @ApiResponses(value = [
 7 @ApiResponse(code = 200, response = CustomSettingResponse, message = 8 ‘Successful setting update'),
 9 @ApiResponse(code = 400, response = ErrorResponse, message = 'Invalid 10 user input'),
 11 @ApiResponse(code = 500, response = ErrorResponse, message = 'Unexpected 12 server error')
 13 ])
 14 CustomSettingResponse setSetting(@RequestBody CustomModel settingsValue) {
 15 SaveSettingUpdateRequest request = new SaveSettingUpdateRequest (
 16 settingsValue.fieldOne,
 17 [new TransformedSetting(SettingEnum.POSSIBLE_ENUM_VALUE, 18 new Double(settingsValue.value))]
 19 )
 20 api.saveUpdatedSetting(request)
 21 } X

Slide 33

Slide 33 text

@codeJENNerator 1 @Secured(‘ROLE_ALLOWED_TO_PERFORM_ACTION’)
 2 @RequestMapping(value = '/v1/serviceName/actionName', method = 3 RequestMethod.POST) 4 CustomSettingResponse setSetting(@RequestBody CustomModel settingsValue) {
 5 SaveSettingUpdateRequest request = new SaveSettingUpdateRequest (
 6 settingsValue.fieldOne,
 7 [new TransformedSetting(SettingEnum.POSSIBLE_ENUM_VALUE, 8 new Double(settingsValue.value))]
 9 )
 10 api.saveUpdatedSetting(request)
 11 }

Slide 34

Slide 34 text

@codeJENNerator Object Mapping img src: https://github.com/springfox/springfox/issues/281

Slide 35

Slide 35 text

@codeJENNerator Advantages

Slide 36

Slide 36 text

@codeJENNerator Swagger UI “Try-It” Button

Slide 37

Slide 37 text

@codeJENNerator The Alternatives

Slide 38

Slide 38 text

@codeJENNerator Postman Collections src: https://www.getpostman.com/img/v1/docs/run_btn_ux/run_btn_ux_1.png

Slide 39

Slide 39 text

@codeJENNerator Curl -> curl 'http://localhost:8080/greetings' -i -H 'Content-Type: text/plain' HTTP/1.1 200 X-Application-Context: application:8080 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Thu, 26 Jan 2017 13:28:19 GMT [{"id":1,"message":"Hello"},{"id":2,"message":"Hi"},{"id":3,"message":"Hola"},{"id": 4,"message":"Olá"},{"id":5,"message":"Hej"}]

Slide 40

Slide 40 text

@codeJENNerator Mixing Spring REST Docs and Swagger

Slide 41

Slide 41 text

@codeJENNerator Swagger2Markup https://swagger2markup.readme.io/

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

@codeJENNerator AssertJ-Swagger https://github.com/RobWin/assertj-swagger FAIL! img src: http://www.elvenspirit.com/elf/wp-content/uploads/2011/10/IMG_3013.jpg

Slide 45

Slide 45 text

@codeJENNerator Test-Driven Documentation Green Red Refactor

Slide 46

Slide 46 text

@codeJENNerator Test-Driven Documentation

Slide 47

Slide 47 text

@codeJENNerator Test-Driven Documentation Red

Slide 48

Slide 48 text

@codeJENNerator Test-Driven Documentation Red

Slide 49

Slide 49 text

@codeJENNerator Test-Driven Documentation Document Red

Slide 50

Slide 50 text

@codeJENNerator Test-Driven Documentation Document Red

Slide 51

Slide 51 text

@codeJENNerator Test-Driven Documentation Document Green Red

Slide 52

Slide 52 text

@codeJENNerator Test-Driven Documentation Document Green Red

Slide 53

Slide 53 text

@codeJENNerator Test-Driven Documentation Document Green Red Refactor

Slide 54

Slide 54 text

@codeJENNerator Test-Driven Documentation Document Green Red Refactor

Slide 55

Slide 55 text

Winning Solution https://flic.kr/p/5XiKxU

Slide 56

Slide 56 text

@codeJENNerator Winning Solution - Ensures documentation matches implementation - Encourages writing more tests - Reduces duplication in docs and tests - Removes annotations from source

Slide 57

Slide 57 text

@codeJENNerator Spring REST Docs

Slide 58

Slide 58 text

@codeJENNerator Game Changers https://flic.kr/p/9Tiv3U

Slide 59

Slide 59 text

@codeJENNerator Game Changers •Generated code snippets •Tests fail when documentation is missing or out-of-date •Rest APIs with Hypermedia •Ratpack •Dynamic routing doesn’t work with Swagger

Slide 60

Slide 60 text

@codeJENNerator Getting Started

Slide 61

Slide 61 text

@codeJENNerator Overview projects.spring.io/spring-restdocs springrestdocs

Slide 62

Slide 62 text

@codeJENNerator Overview •Sponsored by Pivotal •Project Lead - Andy Wilkinson •Current Last Version - 1.2.0 released Monday April 24 •Most Recent Bug Fix Version - 1.1.3 released Monday April 24 •*NEW* Twitter Account and Official Logo

Slide 63

Slide 63 text

@codeJENNerator Other Interesting Talks • Documenting RESTful Apis - SpringOne2GX 2015 Andy Wilkinson • Writing comprehensive and guaranteed up-to-date REST API documentation - SpringOne Platform 2016 Anders Evers • Documenting APIs with Spring REST Docs - Tomasz Kopczynski @t_kopczynski

Slide 64

Slide 64 text

@codeJENNerator Release Highlights

Slide 65

Slide 65 text

1.0.0

Slide 66

Slide 66 text

1.0.0 MockMVC

Slide 67

Slide 67 text

1.0.0 MockMVC AutoGenerated Snippets

Slide 68

Slide 68 text

1.0.0 MockMVC AutoGenerated Snippets AsciiDoctor Integration

Slide 69

Slide 69 text

1.0.0 MockMVC AutoGenerated Snippets AsciiDoctor Integration Hypermedia Support

Slide 70

Slide 70 text

1.1.0 img src: https://flic.kr/p/bwVxge

Slide 71

Slide 71 text

Relaxed and Reusable Snippets 1.1.0 img src: https://flic.kr/p/bwVxge RestAssured

Slide 72

Slide 72 text

Relaxed and Reusable Snippets Markdown 1.1.0 img src: https://flic.kr/p/bwVxge RestAssured TestNG

Slide 73

Slide 73 text

@codeJENNerator Upgrading to 1.1 • RESTDocumentation is now JUnitRestDocumentation or ManualRestDocumentation • Specify special dependency for restassured

Slide 74

Slide 74 text

AsciiDoctor Macro Support Complex Payloads img src: https://www.flickr.com/ photos/dskley/15558668690 1.2.0 JUST RELEASED! Request Body Snippets Response Body Snippets

Slide 75

Slide 75 text

@codeJENNerator Upgrading to 1.2 • If using Rest Assured 3 • add dependency for testCompile "io.rest- assured:rest-assured:3.0.2" • REST Assured 3 changes the package from com.jayway.restassured to io.restassured • Change Spring REST docs support to restassured3 (will show deprecated in IntelliJ and the app will fail)

Slide 76

Slide 76 text

@codeJENNerator AsciiDoctor Module • adds the default configuration in Gradle • removes some boilerplate from the asciidoc files • (see relevant slides)

Slide 77

Slide 77 text

img src: https://flic.kr/p/S9wzGb 2.0

Slide 78

Slide 78 text

Java 8+ Spring 5+ img src: https://flic.kr/p/S9wzGb 2.0 WebTestClient

Slide 79

Slide 79 text

@codeJENNerator Groovier Spring REST docs • Spring Boot • Ratpack • Grails

Slide 80

Slide 80 text

@codeJENNerator

Slide 81

Slide 81 text

@codeJENNerator

Slide 82

Slide 82 text

@codeJENNerator

Slide 83

Slide 83 text

@codeJENNerator Groovier Spring REST docs Example - Spring Boot

Slide 84

Slide 84 text

@codeJENNerator Groovier Spring REST docs Example - Spring Boot • Groovy Spring Boot Project

Slide 85

Slide 85 text

@codeJENNerator Groovier Spring REST docs Example - Spring Boot • Groovy Spring Boot Project + Asciidoctor Gradle plugin

Slide 86

Slide 86 text

@codeJENNerator Groovier Spring REST docs Example - Spring Boot • Groovy Spring Boot Project + Asciidoctor Gradle plugin + MockMVC and documentation to Spock tests

Slide 87

Slide 87 text

@codeJENNerator Groovier Spring REST docs Example - Spring Boot • Groovy Spring Boot Project + Asciidoctor Gradle plugin + MockMVC and documentation to Spock tests + Add to static assets during build and publish to GitHub pages

Slide 88

Slide 88 text

@codeJENNerator Groovy Spring Boot App • Start with lazybones spring boot app • Add mock endpoints for example https://github.com/jlstrater/groovy-spring-boot- restdocs-example

Slide 89

Slide 89 text

@codeJENNerator Endpoints @CompileStatic
 @RestController
 @RequestMapping('/greetings')
 @Slf4j
 class GreetingsController { 
 @RequestMapping(method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> list(@RequestParam(required = false) String message) {
 … }
 
 @RequestMapping(path= '/{id}', method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> getById(@PathVariable String id) {
 … }
 
 @RequestMapping(method = RequestMethod.POST, produces = 'application/json', consumes = 'application/json')
 ResponseEntity> post(@RequestBody Greeting example) {
 … }
 }

Slide 90

Slide 90 text

@codeJENNerator Endpoints @CompileStatic
 @RestController
 @RequestMapping('/greetings')
 @Slf4j
 class GreetingsController { 
 @RequestMapping(method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> list(@RequestParam(required = false) String message) {
 … }
 
 @RequestMapping(path= '/{id}', method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> getById(@PathVariable String id) {
 … }
 
 @RequestMapping(method = RequestMethod.POST, produces = 'application/json', consumes = 'application/json')
 ResponseEntity> post(@RequestBody Greeting example) {
 … }
 } Get all greetings or search by name /greetings or /greetings?message=Hello

Slide 91

Slide 91 text

@codeJENNerator Endpoints @CompileStatic
 @RestController
 @RequestMapping('/greetings')
 @Slf4j
 class GreetingsController { 
 @RequestMapping(method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> list(@RequestParam(required = false) String message) {
 … }
 
 @RequestMapping(path= '/{id}', method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> getById(@PathVariable String id) {
 … }
 
 @RequestMapping(method = RequestMethod.POST, produces = 'application/json', consumes = 'application/json')
 ResponseEntity> post(@RequestBody Greeting example) {
 … }
 } Get all greetings or search by name /greetings or /greetings?message=Hello Get a greeting by id /greetings/1

Slide 92

Slide 92 text

@codeJENNerator Endpoints @CompileStatic
 @RestController
 @RequestMapping('/greetings')
 @Slf4j
 class GreetingsController { 
 @RequestMapping(method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> list(@RequestParam(required = false) String message) {
 … }
 
 @RequestMapping(path= '/{id}', method = RequestMethod.GET, produces = 'application/json')
 ResponseEntity> getById(@PathVariable String id) {
 … }
 
 @RequestMapping(method = RequestMethod.POST, produces = 'application/json', consumes = 'application/json')
 ResponseEntity> post(@RequestBody Greeting example) {
 … }
 } Get all greetings or search by name /greetings or /greetings?message=Hello Get a greeting by id /greetings/1 Create a new greeting /greetings

Slide 93

Slide 93 text

@codeJENNerator

Slide 94

Slide 94 text

@codeJENNerator

Slide 95

Slide 95 text

@codeJENNerator Asciidoctor Gradle Plugin

Slide 96

Slide 96 text

@codeJENNerator Example AsciiDoc = Gr8Data API Guide
 Jenn Strater;
 :doctype: book
 :icons: font
 :source-highlighter: highlightjs
 :toc: left
 :toclevels: 4
 :sectlinks:
 
 [introduction]
 = Introduction
 
 The Gr8Data API is a RESTful web service for aggregating and displaying gender ratios from various companies across the world. This document outlines how to submit data from your company or team and
 how to access the aggregate data.
 
 [[overview-http-verbs]]
 == HTTP verbs
 
 The Gr8Data API tries to adhere as closely as possible to standard HTTP and REST conventions in its use of HTTP verbs.

Slide 97

Slide 97 text

@codeJENNerator Install classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.3'
 apply plugin: 'org.asciidoctor.convert'
 
 asciidoctor {
 sourceDir = file('src/docs')
 outputDir "$projectDir/src/main/resources/public"
 backends 'html5'
 attributes 'source-highlighter' : 'prettify',
 'imagesdir':'images',
 'toc':'left',
 'icons': 'font',
 'setanchors':'true',
 'idprefix':'',
 'idseparator':'-',
 'docinfo1':'true'
 }


Slide 98

Slide 98 text

@codeJENNerator

Slide 99

Slide 99 text

@codeJENNerator Converted to HTML

Slide 100

Slide 100 text

@codeJENNerator

Slide 101

Slide 101 text

@codeJENNerator

Slide 102

Slide 102 text

@codeJENNerator MockMvc Test src: http://www.javacodegeeks.com/2013/04/spring-mvc-introduction-in-testing.html

Slide 103

Slide 103 text

@codeJENNerator Stand Alone Setup class ExampleControllerSpec extends Specification {
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup( new ExampleController()).build()
 }
 
 void 'test and document get by message’() {
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .param('message', ‘Cześć Code Europe!’)
 .contentType(MediaType.APPLICATION_JSON)) then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath(‘message’).value('Cześć Code Europe!’)) } }

Slide 104

Slide 104 text

@codeJENNerator Web Context Setup void setup() {
 this.mockMvc = MockMvcBuilders .webAppContextSetup(this.context) .build()
 }

Slide 105

Slide 105 text

@codeJENNerator Web Context Setup void setup() {
 this.mockMvc = MockMvcBuilders .webAppContextSetup(this.context) .build()
 } If context is null, remember to add spock-spring!!

Slide 106

Slide 106 text

@codeJENNerator

Slide 107

Slide 107 text

@codeJENNerator

Slide 108

Slide 108 text

@codeJENNerator Gradle ext {
 snippetsDir = file('build/generated-snippets')
 } 
 testCompile “org.springframework.restdocs:spring- restdocs-mockmvc:${springRestDocsVersion}" ext['spring-restdocs.version'] = '1.2.0.RELEASE'

Slide 109

Slide 109 text

@codeJENNerator Gradle ext {
 snippetsDir = file('build/generated-snippets')
 } 
 testCompile “org.springframework.restdocs:spring- restdocs-mockmvc:${springRestDocsVersion}" ext['spring-restdocs.version'] = '1.2.0.RELEASE'

Slide 110

Slide 110 text

@codeJENNerator Gradle ext {
 snippetsDir = file('build/generated-snippets')
 } 
 testCompile “org.springframework.restdocs:spring- restdocs-mockmvc:${springRestDocsVersion}" ext['spring-restdocs.version'] = '1.2.0.RELEASE' Spring Boot Specific!

Slide 111

Slide 111 text

@codeJENNerator Gradle asciidoctor {
 dependsOn test
 sourceDir = file('src/docs')
 outputDir "$projectDir/src/main/resources/public"
 + inputs.dir snippetsDir
 backends 'html5'
 attributes 'source-highlighter' : 'prettify',
 'imagesdir':'images',
 'toc':'left',
 'icons': 'font',
 'setanchors':'true',
 'idprefix':'',
 'idseparator':'-',
 'docinfo1':'true',
 + 'snippets': snippetsDir
 }

Slide 112

Slide 112 text

@codeJENNerator With AsciiDoctor Module

Slide 113

Slide 113 text

@codeJENNerator Gradle ext {
 snippetsDir = file('build/generated-snippets')
 } 
 testCompile “org.springframework.restdocs:spring-restdocs- mockmvc:${springRestDocsVersion}" asciidoctor “org.springframework.restdocs:spring-restdocs- asciidoctor:${springRestDocsVersion}" 
 test {
 outputs.dir snippetsDir
 }
 
 asciidoctor {
 dependsOn test
 inputs.dir snippetsDir
 }

Slide 114

Slide 114 text

@codeJENNerator Gradle ext {
 snippetsDir = file('build/generated-snippets')
 } 
 testCompile “org.springframework.restdocs:spring-restdocs- mockmvc:${springRestDocsVersion}" asciidoctor “org.springframework.restdocs:spring-restdocs- asciidoctor:${springRestDocsVersion}" 
 test {
 outputs.dir snippetsDir
 }
 
 asciidoctor {
 dependsOn test
 inputs.dir snippetsDir
 }

Slide 115

Slide 115 text

@codeJENNerator

Slide 116

Slide 116 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 }

Slide 117

Slide 117 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 }

Slide 118

Slide 118 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 }

Slide 119

Slide 119 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } void 'test and document get by message'() {
 
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .param('message', ‘Hello')
 .contentType(MediaType.APPLICATION_JSON))

Slide 120

Slide 120 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath(‘message').value('Hello')) .andDo(document('greetings-get-example', preprocessResponse(prettyPrint()), responseFields(greeting))) } FieldDescriptor[] greeting = new FieldDescriptor().with {
 [fieldWithPath('id').type(JsonFieldType.NUMBER)
 .description("The greeting's id"),
 fieldWithPath('message').type(JsonFieldType.STRING)
 .description("The greeting's message")]
 }
 } void 'test and document get by message'() {
 
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .param('message', ‘Hello')
 .contentType(MediaType.APPLICATION_JSON))

Slide 121

Slide 121 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath(‘message').value('Hello')) .andDo(document('greetings-get-example', preprocessResponse(prettyPrint()), responseFields(greeting))) } FieldDescriptor[] greeting = new FieldDescriptor().with {
 [fieldWithPath('id').type(JsonFieldType.NUMBER)
 .description("The greeting's id"),
 fieldWithPath('message').type(JsonFieldType.STRING)
 .description("The greeting's message")]
 }
 } void 'test and document get by message'() {
 
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .param('message', ‘Hello')
 .contentType(MediaType.APPLICATION_JSON))

Slide 122

Slide 122 text

@codeJENNerator class GreetingsControllerSpec extends Specification {
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath(‘message').value('Hello')) .andDo(document('greetings-get-example', preprocessResponse(prettyPrint()), responseFields(greeting))) } FieldDescriptor[] greeting = new FieldDescriptor().with {
 [fieldWithPath('id').type(JsonFieldType.NUMBER)
 .description("The greeting's id"),
 fieldWithPath('message').type(JsonFieldType.STRING)
 .description("The greeting's message")]
 }
 } void 'test and document get by message'() {
 
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .param('message', ‘Hello')
 .contentType(MediaType.APPLICATION_JSON))

Slide 123

Slide 123 text

@codeJENNerator Special Use Case

Slide 124

Slide 124 text

@codeJENNerator Setup Via Annotation 
 +@WebMvcTest(controllers = GreetingsController)
 +@AutoConfigureRestDocs(
 + outputDir = "build/generated-snippets",
 + uriHost = “greetingsfromcodeeurope.pl",
 + uriPort = 8080
 ) class BaseControllerSpec extends Specification { 
 // @Rule
 // JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation('src/ docs/generated-snippets')
 
 + @Autowired
 protected MockMvc mockMvc
 //
 // @Autowired
 // private WebApplicationContext context
 //
 // void setup() {
 // this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
 // .apply(documentationConfiguration(this.restDocumentation))
 // .build()
 // } }

Slide 125

Slide 125 text

@codeJENNerator

Slide 126

Slide 126 text

@codeJENNerator

Slide 127

Slide 127 text

@codeJENNerator Generated Snippets • curl-request.adoc • http-request.adoc • httpie-request.adoc • http-response.adoc • request body • response body • response-fields.adoc • request-parameters.adoc • request-parts.adoc

Slide 128

Slide 128 text

@codeJENNerator Example Http Response [source,http,options="nowrap"]
 ----
 HTTP/1.1 200 OK
 Content-Type: application/json;charset=UTF-8
 Content-Length: 37
 
 {
 "id" : 1,
 "message" : "Hello"
 }
 ----

Slide 129

Slide 129 text

@codeJENNerator Example Response Fields |===
 |Path|Type|Description
 
 |`id`
 |`Number`
 |The greeting's id
 
 |`message`
 |`String`
 |The greeting's message
 
 |===

Slide 130

Slide 130 text

No content

Slide 131

Slide 131 text

@codeJENNerator Create a new greeting void 'test and document post with example endpoint and custom name'() {
 when:
 ResultActions result = this.mockMvc.perform(post('/greetings')
 .content(new ObjectMapper().writeValueAsString( new Greeting(message: ‘Cześć Code Europe!')))
 .contentType(MediaType.APPLICATION_JSON))
 then:
 result
 .andExpect(status().isCreated())
 .andDo(document('greetings-post-example', requestFields([fieldWithPath(‘id').type(JsonFieldType.NULL) .optional().description("The greeting's id"),
 fieldWithPath('message').type(JsonFieldType.STRING)
 .description("The greeting's message")])
 ))
 }

Slide 132

Slide 132 text

@codeJENNerator Create a new greeting void 'test and document post with example endpoint and custom name'() {
 when:
 ResultActions result = this.mockMvc.perform(post('/greetings')
 .content(new ObjectMapper().writeValueAsString( new Greeting(message: ‘Cześć Code Europe!')))
 .contentType(MediaType.APPLICATION_JSON))
 then:
 result
 .andExpect(status().isCreated())
 .andDo(document('greetings-post-example', requestFields([fieldWithPath(‘id').type(JsonFieldType.NULL) .optional().description("The greeting's id"),
 fieldWithPath('message').type(JsonFieldType.STRING)
 .description("The greeting's message")])
 ))
 }

Slide 133

Slide 133 text

@codeJENNerator List Greetings void 'test and document get of a list of greetings'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .contentType(MediaType.TEXT_PLAIN))
 
 then:
 result
 .andExpect(status().isOk())
 .andDo(document(‘greetings-list-example', preprocessResponse(prettyPrint()),
 responseFields(greetingList)
 ))
 } FieldDescriptor[] greetingList = new FieldDescriptor().with {
 [fieldWithPath('[].id').type(JsonFieldType.NUMBER).optional()
 .description("The greeting's id"),
 fieldWithPath('[].message').type(JsonFieldType.STRING)
 .description("The greeting's message")]
 }

Slide 134

Slide 134 text

@codeJENNerator List Greetings void 'test and document get of a list of greetings'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/greetings')
 .contentType(MediaType.TEXT_PLAIN))
 
 then:
 result
 .andExpect(status().isOk())
 .andDo(document(‘greetings-list-example', preprocessResponse(prettyPrint()),
 responseFields(greetingList)
 ))
 } FieldDescriptor[] greetingList = new FieldDescriptor().with {
 [fieldWithPath('[].id').type(JsonFieldType.NUMBER).optional()
 .description("The greeting's id"),
 fieldWithPath('[].message').type(JsonFieldType.STRING)
 .description("The greeting's message")]
 }

Slide 135

Slide 135 text

@codeJENNerator Path Parameters void 'test and document getting a greeting by id'() {
 when:
 ResultActions result = this.mockMvc.perform( RestDocumentationRequestBuilders.get('/greetings/{id}', 1))
 
 then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath('id').value(1))
 .andDo(document('greetings-get-by-id-example',
 preprocessResponse(prettyPrint()),
 pathParameters(parameterWithName(‘id') .description("The greeting's id")),
 responseFields(greeting)
 ))
 }

Slide 136

Slide 136 text

@codeJENNerator Path Parameters void 'test and document getting a greeting by id'() {
 when:
 ResultActions result = this.mockMvc.perform( RestDocumentationRequestBuilders.get('/greetings/{id}', 1))
 
 then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath('id').value(1))
 .andDo(document('greetings-get-by-id-example',
 preprocessResponse(prettyPrint()),
 pathParameters(parameterWithName(‘id') .description("The greeting's id")),
 responseFields(greeting)
 ))
 }

Slide 137

Slide 137 text

@codeJENNerator

Slide 138

Slide 138 text

@codeJENNerator Failing Tests

Slide 139

Slide 139 text

@codeJENNerator Failing Tests

Slide 140

Slide 140 text

@codeJENNerator Failing Tests

Slide 141

Slide 141 text

@codeJENNerator +

Slide 142

Slide 142 text

@codeJENNerator +

Slide 143

Slide 143 text

@codeJENNerator Add Snippets to AsciiDoc == Errors
 
 Whenever an error response (status code >= 400) is returned, the body will contain a JSON object
 that describes the problem. The error object has the following structure:
 
 include::{snippets}/error-example/response-fields.adoc[]
 
 For example, a request that attempts to apply a non-existent tag to a note will produce a
 `400 Bad Request` response:
 
 include::{snippets}/error-example/http-response.adoc[]
 
 [[resources]]
 = Resources
 
 include::resources/example.adoc[]

Slide 144

Slide 144 text

@codeJENNerator New in 1.2!

Slide 145

Slide 145 text

@codeJENNerator

Slide 146

Slide 146 text

@codeJENNerator Build Docs src/docs index.adoc src/main/ resources/public/ html5 index.html

Slide 147

Slide 147 text

@codeJENNerator Strategies

Slide 148

Slide 148 text

@codeJENNerator Strategies • Hook in asciidoctor with the gradle build task • Run the asciidoctor test separately (but make sure to run AFTER the tests)

Slide 149

Slide 149 text

@codeJENNerator

Slide 150

Slide 150 text

@codeJENNerator http://api.example.com/docs

Slide 151

Slide 151 text

@codeJENNerator Publish Docs to Github Pages publish.gradle buildscript {
 repositories {
 jcenter()
 }
 
 dependencies {
 classpath 'org.ajoberstar:gradle-git:1.1.0'
 }
 }
 
 apply plugin: 'org.ajoberstar.github-pages'
 
 githubPages {
 repoUri = '[email protected]:jlstrater/groovy-spring-boot-restdocs-example.git'
 pages {
 from(file('build/resources/main/public/html5')) }
 }

Slide 152

Slide 152 text

@codeJENNerator Publish Docs to Github Pages publish.gradle buildscript {
 repositories {
 jcenter()
 }
 
 dependencies {
 classpath 'org.ajoberstar:gradle-git:1.1.0'
 }
 }
 
 apply plugin: 'org.ajoberstar.github-pages'
 
 githubPages {
 repoUri = '[email protected]:jlstrater/groovy-spring-boot-restdocs-example.git'
 pages {
 from(file('build/resources/main/public/html5')) }
 } If you use this method, remember to deploy docs at the same time as the project!

Slide 153

Slide 153 text

@codeJENNerator

Slide 154

Slide 154 text

@codeJENNerator http://jlstrater.github.io/groovy-spring-boot-restdocs-example

Slide 155

Slide 155 text

@codeJENNerator Support for Rest-Assured

Slide 156

Slide 156 text

@codeJENNerator Groovier Spring REST docs • Ratpack • Grails

Slide 157

Slide 157 text

@codeJENNerator

Slide 158

Slide 158 text

@codeJENNerator Groovier Spring REST docs Example - Ratpack • Ratpack Example Project • https://github.com/ratpack/example-books • Spring RESTdocs RestAssured • https://github.com/ratpack/example-books/pull/25

Slide 159

Slide 159 text

@codeJENNerator

Slide 160

Slide 160 text

@codeJENNerator

Slide 161

Slide 161 text

@codeJENNerator restdocs.gradle dependencies {
 testCompile ‘org.springframework.restdocs:spring-restdocs-restassured:${springRestDocsVersion}'
 }
 
 ext {
 snippetsDir = file('build/generated-snippets')
 } test {
 outputs.dir snippetsDir
 }
 
 asciidoctor {
 mustRunAfter test
 inputs.dir snippetsDir
 sourceDir = file('src/docs')
 separateOutputDirs = false
 outputDir "$projectDir/src/ratpack/public/docs"
 attributes 'snippets': snippetsDir,
 'source-highlighter': 'prettify',
 'imagesdir': 'images',
 'toc': 'left',
 'icons': 'font',
 'setanchors': 'true',
 'idprefix': '',
 'idseparator': '-',
 'docinfo1': 'true'
 }
 
 build.dependsOn asciidoctor


Slide 162

Slide 162 text

@codeJENNerator build.gradle plugins {
 id "io.ratpack.ratpack-groovy" version "1.2.0"
 . . .
 + id 'org.asciidoctor.convert' version '1.5.3'
 }
 
 repositories {
 jcenter() . . . } 
 //some CI config
 apply from: "gradle/ci.gradle"
 + apply from: "gradle/restdocs.gradle"


Slide 163

Slide 163 text

@codeJENNerator

Slide 164

Slide 164 text

@codeJENNerator

Slide 165

Slide 165 text

@codeJENNerator path(":isbn") {
 def isbn = pathTokens["isbn"]
 
 byMethod {
 get {
 bookService.find(isbn).
 single().
 subscribe { Book book ->
 if (book == null) {
 clientError 404
 } else {
 render book
 }
 }
 } ... }
 }
 
 byMethod {
 get {
 bookService.all().
 toList().
 subscribe { List books ->
 render json(books)
 }
 }
 post {
 parse(jsonNode()).
 observe().
 flatMap { input ->
 bookService.insert(
 input.get("isbn").asText(),
 input.get("quantity").asLong(),
 input.get("price").asDouble()
 )
 }.
 single().
 flatMap {
 bookService.find(it)
 }.
 single().
 subscribe { Book createdBook ->
 render createdBook
 }
 } }

Slide 166

Slide 166 text

@codeJENNerator path(":isbn") {
 def isbn = pathTokens["isbn"]
 
 byMethod {
 get {
 bookService.find(isbn).
 single().
 subscribe { Book book ->
 if (book == null) {
 clientError 404
 } else {
 render book
 }
 }
 } ... }
 }
 
 byMethod {
 get {
 bookService.all().
 toList().
 subscribe { List books ->
 render json(books)
 }
 }
 post {
 parse(jsonNode()).
 observe().
 flatMap { input ->
 bookService.insert(
 input.get("isbn").asText(),
 input.get("quantity").asLong(),
 input.get("price").asDouble()
 )
 }.
 single().
 flatMap {
 bookService.find(it)
 }.
 single().
 subscribe { Book createdBook ->
 render createdBook
 }
 } } Get a book by ISBN /api/books/1932394842

Slide 167

Slide 167 text

@codeJENNerator path(":isbn") {
 def isbn = pathTokens["isbn"]
 
 byMethod {
 get {
 bookService.find(isbn).
 single().
 subscribe { Book book ->
 if (book == null) {
 clientError 404
 } else {
 render book
 }
 }
 } ... }
 }
 
 byMethod {
 get {
 bookService.all().
 toList().
 subscribe { List books ->
 render json(books)
 }
 }
 post {
 parse(jsonNode()).
 observe().
 flatMap { input ->
 bookService.insert(
 input.get("isbn").asText(),
 input.get("quantity").asLong(),
 input.get("price").asDouble()
 )
 }.
 single().
 flatMap {
 bookService.find(it)
 }.
 single().
 subscribe { Book createdBook ->
 render createdBook
 }
 } } Get a book by ISBN /api/books/1932394842 Get all books /api/books

Slide 168

Slide 168 text

@codeJENNerator path(":isbn") {
 def isbn = pathTokens["isbn"]
 
 byMethod {
 get {
 bookService.find(isbn).
 single().
 subscribe { Book book ->
 if (book == null) {
 clientError 404
 } else {
 render book
 }
 }
 } ... }
 }
 
 byMethod {
 get {
 bookService.all().
 toList().
 subscribe { List books ->
 render json(books)
 }
 }
 post {
 parse(jsonNode()).
 observe().
 flatMap { input ->
 bookService.insert(
 input.get("isbn").asText(),
 input.get("quantity").asLong(),
 input.get("price").asDouble()
 )
 }.
 single().
 flatMap {
 bookService.find(it)
 }.
 single().
 subscribe { Book createdBook ->
 render createdBook
 }
 } } Get a book by ISBN /api/books/1932394842 Get all books /api/books Post to create a new book /api/books

Slide 169

Slide 169 text

@codeJENNerator

Slide 170

Slide 170 text

@codeJENNerator

Slide 171

Slide 171 text

Asciidoctor Gradle Plugin (same as before)

Slide 172

Slide 172 text

@codeJENNerator

Slide 173

Slide 173 text

@codeJENNerator

Slide 174

Slide 174 text

@codeJENNerator https://github.com/jayway/rest-assured

Slide 175

Slide 175 text

@codeJENNerator abstract class BaseDocumentationSpec extends Specification {
 
 @Shared
 ApplicationUnderTest aut = new ExampleBooksApplicationUnderTest()
 
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected RequestSpecification documentationSpec
 
 void setup() {
 this.documentationSpec = new RequestSpecBuilder()
 .addFilter(documentationConfiguration(restDocumentation))
 .build()
 }
 }


Slide 176

Slide 176 text

@codeJENNerator class BookDocumentationSpec extends BaseDocumentationSpec {
 
 @Shared
 EmbeddedApp isbndb = GroovyEmbeddedApp.of {
 handlers {
 all {
 render '{"data" : [{"title" : "Learning Ratpack", "publisher_name" : "O\'Reilly Media", "author_data" : [{"id" : "dan_woods", "name" : "Dan Woods"}]}]}'
 }
 }
 }
 
 @Delegate
 TestHttpClient client = aut.httpClient
 RemoteControl remote = new RemoteControl(aut)
 
 
 def setupSpec() {
 System.setProperty('eb.isbndb.host', "http://${isbndb.address.host}:${isbndb.address.port}")
 System.setProperty('eb.isbndb.apikey', "fakeapikey")
 }
 
 def cleanupSpec() {
 System.clearProperty('eb.isbndb.host')
 }
 
 def setupTestBook() {
 requestSpec { RequestSpec requestSpec ->
 requestSpec.body.type("application/json")
 requestSpec.body.text(JsonOutput.toJson([isbn: "1932394842", quantity: 0, price: 22.34]))
 }
 post("api/book")
 }
 
 def cleanup() {
 remote.exec {
 get(Sql).execute("delete from books")
 }
 } . . .

Slide 177

Slide 177 text

@codeJENNerator class BookDocumentationSpec extends BaseDocumentationSpec {
 
 @Shared
 EmbeddedApp isbndb = GroovyEmbeddedApp.of {
 handlers {
 all {
 render '{"data" : [{"title" : "Learning Ratpack", "publisher_name" : "O\'Reilly Media", "author_data" : [{"id" : "dan_woods", "name" : "Dan Woods"}]}]}'
 }
 }
 }
 
 @Delegate
 TestHttpClient client = aut.httpClient
 RemoteControl remote = new RemoteControl(aut)
 
 
 def setupSpec() {
 System.setProperty('eb.isbndb.host', "http://${isbndb.address.host}:${isbndb.address.port}")
 System.setProperty('eb.isbndb.apikey', "fakeapikey")
 }
 
 def cleanupSpec() {
 System.clearProperty('eb.isbndb.host')
 }
 
 def setupTestBook() {
 requestSpec { RequestSpec requestSpec ->
 requestSpec.body.type("application/json")
 requestSpec.body.text(JsonOutput.toJson([isbn: "1932394842", quantity: 0, price: 22.34]))
 }
 post("api/book")
 }
 
 def cleanup() {
 remote.exec {
 get(Sql).execute("delete from books")
 }
 } . . . Setup Test Data and Cleanup After Each Test

Slide 178

Slide 178 text

@codeJENNerator void 'test and document list books'() {
 setup:
 setupTestBook()
 
 expect:
 given(this.documentationSpec)
 .contentType('application/json')
 .accept('application/json')
 .port(aut.address.port)
 .filter(document('books-list-example',
 preprocessRequest(modifyUris()
 .host('books.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('[].isbn').description('The ISBN of the book'),
 fieldWithPath('[].quantity').description("The quantity of the book that is available"),
 fieldWithPath('[].price').description("The current price of the book"),
 fieldWithPath('[].title').description("The title of the book"),
 fieldWithPath('[].author').description('The author of the book'),
 fieldWithPath('[].publisher').description('The publisher of the book')
 )))
 .when()
 .get('/api/book')
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 179

Slide 179 text

@codeJENNerator Response Body Snippet [source,options="nowrap"]
 ----
 [ {
 "isbn" : "1932394842",
 "quantity" : 0,
 "price" : 22.34,
 "title" : "Learning Ratpack",
 "author" : "Dan Woods",
 "publisher" : "O'Reilly Media"
 } ]
 ----

Slide 180

Slide 180 text

@codeJENNerator

Slide 181

Slide 181 text

@codeJENNerator

Slide 182

Slide 182 text

@codeJENNerator

Slide 183

Slide 183 text

@codeJENNerator

Slide 184

Slide 184 text

No content

Slide 185

Slide 185 text

@codeJENNerator Reusable Snippets protected final Snippet getBookFields() {
 responseFields(
 fieldWithPath('isbn').description('The ISBN of the book'),
 fieldWithPath('quantity').description("The quantity of the book that is available"),
 fieldWithPath('price').description("The current price of the book"),
 fieldWithPath('title').description("The title of the book"),
 fieldWithPath('author').description('The author of the book’), fieldWithPath('publisher').description('The publisher of the book’) )
 }

Slide 186

Slide 186 text

@codeJENNerator def "test and document create book"() {
 given:
 def setup = given(this.documentationSpec)
 .body('{"isbn": "1234567890", "quantity": 10, "price": 22.34}')
 .contentType('application/json')
 .accept('application/json')
 .port(aut.address.port)
 .filter(document('books-create-example',
 preprocessRequest(prettyPrint(),
 modifyUris()
 .host('books.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 bookFields,
 requestFields(
 fieldWithPath('isbn').type(JsonFieldType.STRING).description('book ISBN id'),
 fieldWithPath('quantity').type(JsonFieldType.NUMBER).description('quanity available'),
 fieldWithPath('price').type(JsonFieldType.NUMBER)
 .description('price of the item as a number without currency')
 ),))
 when:
 def result = setup
 .when()
 .post("api/book")
 then:
 result
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 187

Slide 187 text

@codeJENNerator def "test and document create book"() {
 given:
 def setup = given(this.documentationSpec)
 .body('{"isbn": "1234567890", "quantity": 10, "price": 22.34}')
 .contentType('application/json')
 .accept('application/json')
 .port(aut.address.port)
 .filter(document('books-create-example',
 preprocessRequest(prettyPrint(),
 modifyUris()
 .host('books.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 bookFields,
 requestFields(
 fieldWithPath('isbn').type(JsonFieldType.STRING).description('book ISBN id'),
 fieldWithPath('quantity').type(JsonFieldType.NUMBER).description('quanity available'),
 fieldWithPath('price').type(JsonFieldType.NUMBER)
 .description('price of the item as a number without currency')
 ),))
 when:
 def result = setup
 .when()
 .post("api/book")
 then:
 result
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 188

Slide 188 text

@codeJENNerator Public APIs

Slide 189

Slide 189 text

@codeJENNerator https://jennstrater.blogspot.dk/2017/01/ using-spring-rest-docs-to-document.html

Slide 190

Slide 190 text

@codeJENNerator

Slide 191

Slide 191 text

@codeJENNerator Groovier Spring REST docs Sample - Grails

Slide 192

Slide 192 text

@codeJENNerator Groovier Spring REST docs Sample - Grails • Grails 3.2.6

Slide 193

Slide 193 text

@codeJENNerator Groovier Spring REST docs Sample - Grails • Grails 3.2.6 + Asciidoctor Gradle plugin

Slide 194

Slide 194 text

@codeJENNerator Groovier Spring REST docs Sample - Grails • Grails 3.2.6 + Asciidoctor Gradle plugin + Spring REST docs - RestAssured

Slide 195

Slide 195 text

@codeJENNerator

Slide 196

Slide 196 text

@codeJENNerator package com.example
 
 import grails.rest.Resource
 
 @Resource(uri='/notes', readOnly = false, formats = ['json', 'xml'])
 class Note {
 Long id
 String title
 String body
 
 static hasMany = [tags: Tag]
 static mapping = {
 tags joinTable: [name: "mm_notes_tags", key: 'mm_note_id' ]
 }
 }

Slide 197

Slide 197 text

@codeJENNerator package com.example import grails.rest.Resource
 @Resource(uri='/tags', readOnly = false, formats = ['json', 'xml'])
 class Tag {
 Long id
 String name
 
 static hasMany = [notes: Note]
 static belongsTo = Note
 static mapping = {
 notes joinTable: [name: "mm_notes_tags", key: 'mm_tag_id']
 }
 }

Slide 198

Slide 198 text

@codeJENNerator

Slide 199

Slide 199 text

@codeJENNerator

Slide 200

Slide 200 text

Asciidoctor Gradle Plugin (same as before)

Slide 201

Slide 201 text

@codeJENNerator

Slide 202

Slide 202 text

@codeJENNerator

Slide 203

Slide 203 text

@codeJENNerator https://github.com/jayway/rest-assured (same as before)

Slide 204

Slide 204 text

@codeJENNerator Grails Specific Setup + testCompile “org.springframework.restdocs:spring-restdocs- restassured:${springRestDocsVersion}” asciidoctor { … + mustRunAfter integrationTest … }

Slide 205

Slide 205 text

@codeJENNerator @Integration
 @Rollback
 class ApiDocumentationSpec extends Specification {
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected RequestSpecification documentationSpec
 
 void setup() {
 this.documentationSpec = new RequestSpecBuilder()
 .addFilter(documentationConfiguration(restDocumentation))
 .build()
 } }

Slide 206

Slide 206 text

@codeJENNerator @Integration
 @Rollback
 class ApiDocumentationSpec extends Specification {
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()
 
 protected RequestSpecification documentationSpec
 
 void setup() {
 this.documentationSpec = new RequestSpecBuilder()
 .addFilter(documentationConfiguration(restDocumentation))
 .build()
 } }

Slide 207

Slide 207 text

@codeJENNerator void 'test and document notes list request'() {
 expect:
 given(this.documentationSpec)
 .accept(MediaType.APPLICATION_JSON.toString())
 .filter(document('notes-list-example',
 preprocessRequest(modifyUris()
 .host('api.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('[].class').description('the class of the resource'),
 fieldWithPath('[].id').description('the id of the note'),
 fieldWithPath('[].title').description('the title of the note'),
 fieldWithPath('[].body').description('the body of the note'),
 subsectionWithPath(‘tags').type(JsonFieldType.ARRAY) .description('a list of tags associated with the note'),
 )))
 .when()
 .port(8080)
 .get('/notes')
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 208

Slide 208 text

@codeJENNerator void 'test and document notes list request'() {
 expect:
 given(this.documentationSpec)
 .accept(MediaType.APPLICATION_JSON.toString())
 .filter(document('notes-list-example',
 preprocessRequest(modifyUris()
 .host('api.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('[].class').description('the class of the resource'),
 fieldWithPath('[].id').description('the id of the note'),
 fieldWithPath('[].title').description('the title of the note'),
 fieldWithPath('[].body').description('the body of the note'),
 subsectionWithPath(‘tags').type(JsonFieldType.ARRAY) .description('a list of tags associated with the note'),
 )))
 .when()
 .port(8080)
 .get('/notes')
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 209

Slide 209 text

@codeJENNerator Response Body Snippet |===
 |Path|Type|Description
 
 |`id`
 |`Number`
 |the id of the note
 
 |`title`
 |`String`
 |the title of the note
 
 |`body`
 |`String`
 |the body of the note
 
 |`tags`
 |`Array`
 |the list of tags associated with the note
 
 |===

Slide 210

Slide 210 text

@codeJENNerator

Slide 211

Slide 211 text

No content

Slide 212

Slide 212 text

@codeJENNerator Outcomes

Slide 213

Slide 213 text

@codeJENNerator One Year Later • Made it to production! :) • Team still happy with Spring REST Docs • Other dev teams like to see the examples

Slide 214

Slide 214 text

@codeJENNerator Read the docs for more on.. • Adding Security and Headers • Documenting Constraints • Hypermedia Support • XML Support • Using Markdown instead of Asciidoc • Third Party Extensions for WireMock and Jersey

Slide 215

Slide 215 text

@codeJENNerator Conclusion

Slide 216

Slide 216 text

@codeJENNerator

Slide 217

Slide 217 text

@codeJENNerator • API documentation is complex

Slide 218

Slide 218 text

@codeJENNerator • API documentation is complex • Choosing the right tool for the job not just about the easiest one to setup

Slide 219

Slide 219 text

@codeJENNerator • API documentation is complex • Choosing the right tool for the job not just about the easiest one to setup • Spring REST Docs is a promising tool to enforce good testing and documentation practices without muddying source code.

Slide 220

Slide 220 text

@codeJENNerator • API documentation is complex • Choosing the right tool for the job not just about the easiest one to setup • Spring REST Docs is a promising tool to enforce good testing and documentation practices without muddying source code. • I still hate writing boilerplate documentation, but at least it’s a little less painful now.

Slide 221

Slide 221 text

@codeJENNerator Next Steps • Join the Groovy Community on Slack groovycommunity.com • Join #spring-restdocs on gitter https://gitter.im/spring-projects/ spring-restdocs • Gr8Conf EU May 31 - June 2, 2017 in Copenhagen, Denmark gr8conf.eu

Slide 222

Slide 222 text

@codeJENNerator Questions? https://github.com/jlstrater/groovy-spring-boot-restdocs-example https://github.com/ratpack/example-books https://github.com/jlstrater/spring-restdocs-public-api-example https://flic.kr/p/5DeuzB