Slide 1

Slide 1 text

A Test-Driven Approach to Documenting RESTful APIs with Spring REST Docs Jenn Strater @jennstrater Object Partners Tech Talk March 18, 2016

Slide 2

Slide 2 text

About Me

Slide 3

Slide 3 text

About Me • Senior Consultant at Object Partners, Inc.

Slide 4

Slide 4 text

About Me • Senior Consultant at Object Partners, Inc. • Co-Founder of Gr8Ladies

Slide 5

Slide 5 text

About Me • Senior Consultant at Object Partners, Inc. • Co-Founder of Gr8Ladies • 2016 - 2017 Fulbright US Student Program Selectee to Denmark

Slide 6

Slide 6 text

Background

Slide 7

Slide 7 text

Background • Creating RESTful APIs with Groovy • Spring Boot • Grails • Ratpack

Slide 8

Slide 8 text

Background • Creating RESTful APIs with Groovy • Spring Boot • Grails • Ratpack • Documentation • Swagger • Asciidoctor

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

Factors in Choosing a Documentation Solution

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

Endpoint Vs Resource Design

Slide 15

Slide 15 text

Endpoint Vs Resource Design VS

Slide 16

Slide 16 text

Central Information Security Http Verbs Error Handling Http Status

Slide 17

Slide 17 text

Multiple Services

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

Versioning v1 v2 v3

Slide 20

Slide 20 text

Swagger

Slide 21

Slide 21 text

Swagger Approaches

Slide 22

Slide 22 text

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

Slide 23

Slide 23 text

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

Slide 24

Slide 24 text

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 25

Slide 25 text

Considerations

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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 28

Slide 28 text

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 29

Slide 29 text

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 30

Slide 30 text

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 31

Slide 31 text

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 32

Slide 32 text

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

Slide 33

Slide 33 text

Advantages

Slide 34

Slide 34 text

Swagger UI “Try-It” Button

Slide 35

Slide 35 text

Postman Run Button src: https://www.getpostman.com/img/v1/docs/run_btn_ux/run_btn_ux_1.png

Slide 36

Slide 36 text

Notable Alternatives & Enhancements

Slide 37

Slide 37 text

Swagger2Markup https://swagger2markup.readme.io/

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

Test-Driven Documentation Green Red Refactor

Slide 42

Slide 42 text

Test-Driven Documentation

Slide 43

Slide 43 text

Test-Driven Documentation Red

Slide 44

Slide 44 text

Test-Driven Documentation Red

Slide 45

Slide 45 text

Test-Driven Documentation Document Red

Slide 46

Slide 46 text

Test-Driven Documentation Document Red

Slide 47

Slide 47 text

Test-Driven Documentation Document Green Red

Slide 48

Slide 48 text

Test-Driven Documentation Document Green Red

Slide 49

Slide 49 text

Test-Driven Documentation Document Green Red Refactor

Slide 50

Slide 50 text

Test-Driven Documentation Document Green Red Refactor

Slide 51

Slide 51 text

Advantages • Ensure documentation matches implementation • Encourages writing more tests • Reduces duplication in docs and tests • Removes annotations from source

Slide 52

Slide 52 text

Spring REST Docs

Slide 53

Slide 53 text

Game Changers • Generated code snippets • Tests fail when documentation is missing or out-of- date • Supports Level III Rest APIs (Hypermedia)

Slide 54

Slide 54 text

Getting Started • Documentation - Spring Projects • Documenting RESTful Apis - SpringOne2GX 2015 - Andy Wilkinson • Spring REST Docs - Documenting RESTful APIs using your tests - Devoxx Belgium 2015 - Anders Evers

Slide 55

Slide 55 text

Groovier Spring REST docs • Spring Boot • Grails • Ratpack

Slide 56

Slide 56 text

Groovier Spring REST docs Example I

Slide 57

Slide 57 text

Groovier Spring REST docs Example I • Groovy Spring Boot Project • Level I/II Rest API

Slide 58

Slide 58 text

Groovier Spring REST docs Example I • Groovy Spring Boot Project • Level I/II Rest API + Asciidoctor Gradle plugin

Slide 59

Slide 59 text

Groovier Spring REST docs Example I • Groovy Spring Boot Project • Level I/II Rest API + Asciidoctor Gradle plugin + MockMVC and documentation to Spock tests

Slide 60

Slide 60 text

Groovier Spring REST docs Example I • Groovy Spring Boot Project • Level I/II Rest API + Asciidoctor Gradle plugin + MockMVC and documentation to Spock tests + Add to static assets during build

Slide 61

Slide 61 text

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 62

Slide 62 text

Endpoints @CompileStatic
 @RestController
 @RequestMapping('/hello')
 @Slf4j
 class ExampleController {
 
 @RequestMapping(method = RequestMethod.GET, produces = 'application/json', consumes = 'application/json')
 Example list() {
 new Example(name: 'World')
 }
 
 @RequestMapping(method = RequestMethod.POST, produces = 'application/json', consumes = 'application/json')
 Example list(@RequestBody Example example) {
 example
 }
 }

Slide 63

Slide 63 text

Asciidoctor Gradle Plugin

Slide 64

Slide 64 text

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 65

Slide 65 text

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 66

Slide 66 text

Converted to HTML

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

Stand Alone Setup class ExampleControllerSpec extends Specification {
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup( new ExampleController()).build()
 }
 
 void 'test and document get with example endpoint’() {
 when:
 ResultActions result = this.mockMvc.perform( get(‘/hello’).contentType(MediaType.APPLICATION_JSON)) then:
 result .andExpect(status().isOk()) .andExpect(jsonPath("name").value("World"))
 .andExpect(jsonPath("message").value("Hello, World!”)) }

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

Spring REST docs

Slide 72

Slide 72 text

Gradle ext {
 snippetsDir = file( 'src/docs/generated-snippets')
 } testCompile “org.springframework.restdocs:spring- restdocs-mockmvc:1.0.1.RELEASE”


Slide 73

Slide 73 text

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 74

Slide 74 text

Setup & GET

Slide 75

Slide 75 text

Setup & GET class ExampleControllerSpec extends Specification {
 
 @Rule
 RestDocumentation restDocumentation = new RestDocumentation('src/docs/generated- snippets')
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 }

Slide 76

Slide 76 text

Setup & GET class ExampleControllerSpec extends Specification {
 
 @Rule
 RestDocumentation restDocumentation = new RestDocumentation('src/docs/generated- snippets')
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 }

Slide 77

Slide 77 text

Setup & GET class ExampleControllerSpec extends Specification {
 
 @Rule
 RestDocumentation restDocumentation = new RestDocumentation('src/docs/generated- snippets')
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } void 'test and document get with example endpoint'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/hello')
 .contentType(MediaType.APPLICATION_JSON))

Slide 78

Slide 78 text

Setup & GET class ExampleControllerSpec extends Specification {
 
 @Rule
 RestDocumentation restDocumentation = new RestDocumentation('src/docs/generated- snippets')
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } void 'test and document get with example endpoint'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/hello')
 .contentType(MediaType.APPLICATION_JSON)) then:
 result
 .andExpect(status().isOk()) .andExpect(jsonPath('name').value('World'))
 .andExpect(jsonPath('message').value('Hello, World!'))
 .andDo(document('hello-get-example', preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('name').type(JsonFieldType.STRING).description('name'),
 fieldWithPath('message').type(JsonFieldType.STRING).description('hello world'))
 ))
 }
 }

Slide 79

Slide 79 text

Setup & GET class ExampleControllerSpec extends Specification {
 
 @Rule
 RestDocumentation restDocumentation = new RestDocumentation('src/docs/generated- snippets')
 
 protected MockMvc mockMvc
 
 void setup() {
 this.mockMvc = MockMvcBuilders.standaloneSetup(new ExampleController())
 .apply(documentationConfiguration(this.restDocumentation))
 .build()
 } void 'test and document get with example endpoint'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/hello')
 .contentType(MediaType.APPLICATION_JSON)) then:
 result
 .andExpect(status().isOk()) .andExpect(jsonPath('name').value('World'))
 .andExpect(jsonPath('message').value('Hello, World!'))
 .andDo(document('hello-get-example', preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('name').type(JsonFieldType.STRING).description('name'),
 fieldWithPath('message').type(JsonFieldType.STRING).description('hello world'))
 ))
 }
 }

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

POST

Slide 82

Slide 82 text

POST void 'test and document post with example endpoint and custom name'() {
 when: ResultActions result = this.mockMvc.perform(post(‘/hello') .content(new ObjectMapper() .writeValueAsString(new Example(name: 'mockmvc test’)) .contentType(MediaType.APPLICATION_JSON))

Slide 83

Slide 83 text

POST void 'test and document post with example endpoint and custom name'() {
 when: ResultActions result = this.mockMvc.perform(post(‘/hello') .content(new ObjectMapper() .writeValueAsString(new Example(name: 'mockmvc test’)) .contentType(MediaType.APPLICATION_JSON)) then:
 result
 .andExpect(status().isOk())
 .andExpect(jsonPath('name').value('mockmvc test'))
 .andExpect(jsonPath('message').value('Hello, mockmvc test!')) .andDo(document('hello-post-example', preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('name').type(JsonFieldType.STRING)
 .description('name'),
 fieldWithPath('message').type(JsonFieldType.STRING)
 .description('hello world'))
 ))
 }

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

List Example void 'test and document get of a list from example endpoint'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/hello/list')
 .contentType(MediaType.APPLICATION_JSON))
 
 then:
 result
 .andExpect(status().isOk())
 .andDo(document('hello-list-example', preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('[].message').type(JsonFieldType.STRING)
 .description('message'))
 ))
 }

Slide 86

Slide 86 text

List Example void 'test and document get of a list from example endpoint'() {
 when:
 ResultActions result = this.mockMvc.perform(get('/hello/list')
 .contentType(MediaType.APPLICATION_JSON))
 
 then:
 result
 .andExpect(status().isOk())
 .andDo(document('hello-list-example', preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath('[].message').type(JsonFieldType.STRING)
 .description('message'))
 ))
 }

Slide 87

Slide 87 text

Central Info - Errors void 'test and document error format’() { when:
 ResultActions result = this.mockMvc.perform(put('/error')
 .contentType(MediaType.APPLICATION_JSON)
 .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 405)
 .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, '/hello')
 .requestAttr(RequestDispatcher.ERROR_MESSAGE, "Request method 'PUT' not supported"))


Slide 88

Slide 88 text

Central Info - Errors void 'test and document error format’() { when:
 ResultActions result = this.mockMvc.perform(put('/error')
 .contentType(MediaType.APPLICATION_JSON)
 .requestAttr(RequestDispatcher.ERROR_STATUS_CODE, 405)
 .requestAttr(RequestDispatcher.ERROR_REQUEST_URI, '/hello')
 .requestAttr(RequestDispatcher.ERROR_MESSAGE, "Request method 'PUT' not supported"))
 then:
 result .andExpect(status().isMethodNotAllowed())
 .andDo(document('error-example', preprocessResponse(prettyPrint()),
 responseFields(
 fieldWithPath(‘error') .description('The HTTP error that occurred, e.g. `Bad Request`'),
 fieldWithPath(‘message') .description('A description of the cause of the error'),
 fieldWithPath('path').description('The path to which the request was made'),
 fieldWithPath('status').description('The HTTP status code, e.g. `400`'),
 fieldWithPath(‘timestamp') .description('The time, in milliseconds, at which the error occurred'))
 ))
 }

Slide 89

Slide 89 text

Failing Tests

Slide 90

Slide 90 text

Failing Tests

Slide 91

Slide 91 text

Generated Snippets {example-name} • curl-request.adoc • http-request.adoc • http-response.adoc • response-fields.adoc • request-parameters.adoc src/docs/ generated-snippets

Slide 92

Slide 92 text

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 93

Slide 93 text

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

Slide 94

Slide 94 text

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

Slide 95

Slide 95 text

Rest Assured - 1.1.0 Grails & Ratpack img src: https://www.flickr.com/photos/dskley/15558668690

Slide 96

Slide 96 text

Groovier Spring REST docs Example II

Slide 97

Slide 97 text

Groovier Spring REST docs Example II • Grails 3.0.15 with Web API Profile • Level II Rest API

Slide 98

Slide 98 text

Groovier Spring REST docs Example II • Grails 3.0.15 with Web API Profile • Level II Rest API + Asciidoctor Gradle plugin

Slide 99

Slide 99 text

Groovier Spring REST docs Example II • Grails 3.0.15 with Web API Profile • Level II Rest API + Asciidoctor Gradle plugin + RestAssured and spring REST docs 1.1.0.M1

Slide 100

Slide 100 text

Groovier Spring REST docs Example II • Grails 3.0.15 with Web API Profile • Level II Rest API + Asciidoctor Gradle plugin + RestAssured and spring REST docs 1.1.0.M1 + Publish to Github Pages

Slide 101

Slide 101 text

Simple Grails App

Slide 102

Slide 102 text

Simple Grails App ->grails create-app —profile=web-api —inplace grails> create-domain-resource com.example.Note | Created grails-app/domain/com/example/Note.groovy | Created src/test/groovy/com/example/NoteSpec.groovy grails> create-domain-resource com.example.Tag | Created grails-app/domain/com/example/Tag.groovy | Created src/test/groovy/com/example/TagSpec.groovy

Slide 103

Slide 103 text

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 104

Slide 104 text

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 105

Slide 105 text

Asciidoctor Gradle Plugin

Slide 106

Slide 106 text

Spring REST docs & https://github.com/jayway/rest-assured

Slide 107

Slide 107 text

+ testCompile “org.springframework.restdocs:spring- restdocs-restassured:1.1.0.M1” asciidoctor { … + mustRunAfter integrationTest … }

Slide 108

Slide 108 text

@Integration
 @Rollback
 class ApiDocumentationSpec extends Specification {
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation('src/docs/generated-snippets')
 
 protected RequestSpecification documentationSpec
 
 void setup() {
 this.documentationSpec = new RequestSpecBuilder()
 .addFilter(documentationConfiguration(restDocumentation))
 .build()
 } }

Slide 109

Slide 109 text

@Integration
 @Rollback
 class ApiDocumentationSpec extends Specification {
 @Rule
 JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation('src/docs/generated-snippets')
 
 protected RequestSpecification documentationSpec
 
 void setup() {
 this.documentationSpec = new RequestSpecBuilder()
 .addFilter(documentationConfiguration(restDocumentation))
 .build()
 } }

Slide 110

Slide 110 text

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'),
 fieldWithPath(‘[].tags').type(JsonFieldType.ARRAY) .description('the list of tags associated with the note'),
 )))
 .when()
 .port(8080)
 .get('/notes')
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 111

Slide 111 text

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'),
 fieldWithPath(‘[].tags').type(JsonFieldType.ARRAY) .description('the list of tags associated with the note'),
 )))
 .when()
 .port(8080)
 .get('/notes')
 .then()
 .assertThat()
 .statusCode(is(200))
 }

Slide 112

Slide 112 text

void 'test and document create new note'() {
 expect:
 given(this.documentationSpec)
 .accept(MediaType.APPLICATION_JSON.toString())
 .contentType(MediaType.APPLICATION_JSON.toString())
 .filter(document('notes-create-example',
 preprocessRequest(modifyUris()
 .host('api.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 requestFields(
 fieldWithPath('title').description('the title of the note'),
 fieldWithPath('body').description('the body of the note'),
 fieldWithPath(‘tags').type(JsonFieldType.ARRAY) .description('a list of tags associated to the note')
 ),
 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'),
 fieldWithPath(‘tags').type(JsonFieldType.ARRAY) .description('the list of tags associated with the note'),
 )))
 .body('{ "body": "My test example", "title": "Eureka!", "tags": [{"name": "testing123"}] }')
 .when()
 .port(8080)
 .post('/notes')
 .then()
 .assertThat()
 .statusCode(is(201))
 }

Slide 113

Slide 113 text

void 'test and document create new note'() {
 expect:
 given(this.documentationSpec)
 .accept(MediaType.APPLICATION_JSON.toString())
 .contentType(MediaType.APPLICATION_JSON.toString())
 .filter(document('notes-create-example',
 preprocessRequest(modifyUris()
 .host('api.example.com')
 .removePort()),
 preprocessResponse(prettyPrint()),
 requestFields(
 fieldWithPath('title').description('the title of the note'),
 fieldWithPath('body').description('the body of the note'),
 fieldWithPath(‘tags').type(JsonFieldType.ARRAY) .description('a list of tags associated to the note')
 ),
 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'),
 fieldWithPath(‘tags').type(JsonFieldType.ARRAY) .description('the list of tags associated with the note'),
 )))
 .body('{ "body": "My test example", "title": "Eureka!", "tags": [{"name": "testing123"}] }')
 .when()
 .port(8080)
 .post('/notes')
 .then()
 .assertThat()
 .statusCode(is(201))
 }

Slide 114

Slide 114 text

Publish Docs 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/grails-spring-boot-restdocs-example.git'
 pages {
 from(file('build/docs'))
 }
 }

Slide 115

Slide 115 text

https://jlstrater.github.io/grails-spring-restdocs-example

Slide 116

Slide 116 text

Read the docs for more on.. • Adding Security and Headers • Documenting Constraints • Hypermedia Support • Using Markdown instead of Asciidoc http://projects.spring.io/spring-restdocs/

Slide 117

Slide 117 text

Conclusion • 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 118

Slide 118 text

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