KEMBAR78
Test-Driven Documentation for your REST(ful) service | PDF
Test-Driven Documentation
for your RESTful service
by Jeroen Reijn
JEROEN REIJN
Software Architect at Luminis /Amsterdam
• Focus on productivity and Developer Experience
• Been building APIs for the Web since 2010
• Writes most of his code in Java
• Tweets @jreijn
Let’s talk about Web APIs
source: https://www.programmableweb.com/
Streaming
1%
RPC
10%
REST
89%
REST RPC Streaming GraphQL
source: https://www.programmableweb.com/
REST
Source: http://geek-and-poke.com/geekandpoke/2013/6/14/insulting-made-easy
Richardson Maturity Model
Source: https://www.martinfowler.com/articles/richardsonMaturityModel.html
HATEOAS
(Hypermedia as the Engine of Application State)
REST
• Uniform interface
• Resources
• URIs
• Representations
• Hypermedia
Hypermedia
• Links in resource representations
• State navigations discoverable
Hypertext link specifications
• HAL
• JSON-LD
• JSON API
• Collection+JSON
• Siren
Hypertext link specifications
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/"
},
"planets" : {
"href" : "http://localhost:8080/planets"
},
"people" : {
"href" : "http://localhost:8080/people"
}
}
}
Building an API
Design
BuildDocument
Let’s talk about API design
Specification driven
vs
Code driven
Specification Driven Design
Contract Driven Design
a.k.a
Manual spec
API design
RAML
• RESTful API Modelling Language (RAML)
• Based on YAML file format
• Powerful designer api with auto completion
• Code generation for Java
• No native support for HATEOAS
API Blueprint / Apiary
• Markdown flavoured syntax
• Powerful designer UI
• Documentation while designing
• Java code generator support is *very* minimal
Postman
• Postman client is great for testing APIs
• Supports designing & documenting APIs
• Has support for Api Mocks
• Enables fast prototyping of APIs
• Tools for different phases in the API lifecycle
Open API
• Widely adopted community-driven specification for REST APIs
• YAML and JSON based format
• Programming language-agnostic interface
• Allows both code first and contract first approaches to API design
• Evolving specification (version 3.0 released in the summer of 2017)
Swagger
• Tools around the OpenAPI specification
• Swagger editor
• Swagger-UI
• Swagger Codegen (server and client libs and many languages)
• Swagger Inspector
Swagger Codegen
/**
* Unique identifier representing a specific planet.
* @return id
**/
@ApiModelProperty(value = "Unique identifier representing a specific planet.")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Planet name(String name) {
this.name = name;
return this;
}
Retrospect
• API Design tools and platform are getting really powerful
• OpenAPI seems to be the most widely adopted api spec
• Generating code from your API specification is up to you
Code Driven Design
“ An API is only as good 

as its documentation! ”
Let’s talk about API documentation
Manual documentation
Documentation based on specs
HTML / PDF
Docs based on code
@GetMapping(value = "/films/{id}")
ResponseEntity<Film> getFilmById(@PathVariable(“id") String id);
Docs based on code
@ApiOperation(value = "",
nickname = “getfilmbyid",
notes = "Get a specific film by id.",
response = Film.class,
authorizations = {
@Authorization(value = "apikeyQuery")
}, tags = {})
@ApiResponses(value = {
@ApiResponse(code = 200,
message = "A film.",
response = Film.class)})
@GetMapping(value = “/films/{id}")
ResponseEntity<Film> getFilmById(@ApiParam(value = "Id of the film.", required = true)
@PathVariable("id") String id);
Swagger drawbacks
• Hypermedia support not ‘final’
• Documentation is done through several annotations which are added in your
implementation classes
• API Implementation code overtime, gets overwhelmed with annotations
• Documentation is URI centric
• Documentation and API could become out-of-sync overtime
“ API documentation needs to be
more then just endpoints and
resources ”
Spring REST Docs
“Document RESTful services by combining 

hand-written documentation with 

auto-generated snippets 

produced with Spring MVC Test.”
Spring REST Docs
• Documentation is built from tests
• Supports hypermedia (HATEOAS) APIs
• Immediate reaction to API changes
• Keeps your code clean
• Produces AsciiDoc snippets
Basic Spring MVC Test
@Test
public void testGetAllPlanets() throws Exception {
mockMvc.perform(get("/planets").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()",is(2)));
}
With Spring REST Doc
@Test
public void testGetAllPlanets() throws Exception {
mockMvc.perform(get("/planets").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()",is(2)))
.andDo(document("planets/get"));
}
AsciiDoc snippets
|===
|Path|Type|Description
|`id`
|`Number`
|The id of the planet
|`name`
|`String`
|The name of the planet
|`diameter`
|`Number`
|The diameter of the planet
|===
AsciiDoc
Plain-text writing format. AsciiDoc documents can be translated into various formats, including
HTML, DocBook, PDF and ePub.
= Hello, DevCon!
Jeroen Reijn <jeroen.reijn@luminis.eu>
An introduction to documenting Hypermedia APIs with
https://projects.spring.io/spring-restdocs/[Spring REST Docs].
== First Section
* item 1
* item 2
Generating documentation
Test
Generated
snippets
AsciiDoctor pluginHand-written
docs
Code
Document
Let’s build an API!
Spring Auto REST Docs
• Extension for Spring REST Docs
• Response field documentation generated by means of introspection
• Partial support for documenting Hypermedia ‘links’ out of the box
• DRY - Uses JavaDoc for generating documentation
Spring REST Docs advantages
• Ability to focus on domain model rather than URI’s
• ‘Guarantees’ that API documentation and implementation code are in-sync
• Forces you to update documentation for any implementation changes
• Ability to document with different payloads and explain different test scenarios
• Ability to document remote APIs (with WebTestClient)
In retrospect
• Documenting Hypermedia API is getting easier
• Validating APIs against their documentation is still ‘hard’
• Spring REST Docs can help documenting and validating the API
• Good documentation is key to working with an API
Those who stand for nothing,
fall for anything - Alexander
Hamilton
?Thank you
Questions? is powered by
Don’t forget to vote!

Test-Driven Documentation for your REST(ful) service

  • 1.
    Test-Driven Documentation for yourRESTful service by Jeroen Reijn
  • 2.
    JEROEN REIJN Software Architectat Luminis /Amsterdam • Focus on productivity and Developer Experience • Been building APIs for the Web since 2010 • Writes most of his code in Java • Tweets @jreijn
  • 3.
  • 4.
  • 5.
    Streaming 1% RPC 10% REST 89% REST RPC StreamingGraphQL source: https://www.programmableweb.com/
  • 6.
  • 7.
  • 8.
    Richardson Maturity Model Source:https://www.martinfowler.com/articles/richardsonMaturityModel.html HATEOAS (Hypermedia as the Engine of Application State)
  • 9.
    REST • Uniform interface •Resources • URIs • Representations • Hypermedia
  • 10.
    Hypermedia • Links inresource representations • State navigations discoverable
  • 11.
    Hypertext link specifications •HAL • JSON-LD • JSON API • Collection+JSON • Siren
  • 12.
    Hypertext link specifications { "_links": { "self" : { "href" : "http://localhost:8080/" }, "planets" : { "href" : "http://localhost:8080/planets" }, "people" : { "href" : "http://localhost:8080/people" } } }
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
    RAML • RESTful APIModelling Language (RAML) • Based on YAML file format • Powerful designer api with auto completion • Code generation for Java • No native support for HATEOAS
  • 21.
    API Blueprint /Apiary • Markdown flavoured syntax • Powerful designer UI • Documentation while designing • Java code generator support is *very* minimal
  • 23.
    Postman • Postman clientis great for testing APIs • Supports designing & documenting APIs • Has support for Api Mocks • Enables fast prototyping of APIs • Tools for different phases in the API lifecycle
  • 25.
    Open API • Widelyadopted community-driven specification for REST APIs • YAML and JSON based format • Programming language-agnostic interface • Allows both code first and contract first approaches to API design • Evolving specification (version 3.0 released in the summer of 2017)
  • 26.
    Swagger • Tools aroundthe OpenAPI specification • Swagger editor • Swagger-UI • Swagger Codegen (server and client libs and many languages) • Swagger Inspector
  • 29.
    Swagger Codegen /** * Uniqueidentifier representing a specific planet. * @return id **/ @ApiModelProperty(value = "Unique identifier representing a specific planet.") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Planet name(String name) { this.name = name; return this; }
  • 30.
    Retrospect • API Designtools and platform are getting really powerful • OpenAPI seems to be the most widely adopted api spec • Generating code from your API specification is up to you
  • 31.
  • 33.
    “ An APIis only as good 
 as its documentation! ”
  • 34.
    Let’s talk aboutAPI documentation
  • 36.
  • 37.
    Documentation based onspecs HTML / PDF
  • 38.
    Docs based oncode @GetMapping(value = "/films/{id}") ResponseEntity<Film> getFilmById(@PathVariable(“id") String id);
  • 39.
    Docs based oncode @ApiOperation(value = "", nickname = “getfilmbyid", notes = "Get a specific film by id.", response = Film.class, authorizations = { @Authorization(value = "apikeyQuery") }, tags = {}) @ApiResponses(value = { @ApiResponse(code = 200, message = "A film.", response = Film.class)}) @GetMapping(value = “/films/{id}") ResponseEntity<Film> getFilmById(@ApiParam(value = "Id of the film.", required = true) @PathVariable("id") String id);
  • 41.
    Swagger drawbacks • Hypermediasupport not ‘final’ • Documentation is done through several annotations which are added in your implementation classes • API Implementation code overtime, gets overwhelmed with annotations • Documentation is URI centric • Documentation and API could become out-of-sync overtime
  • 42.
    “ API documentationneeds to be more then just endpoints and resources ”
  • 43.
    Spring REST Docs “DocumentRESTful services by combining 
 hand-written documentation with 
 auto-generated snippets 
 produced with Spring MVC Test.”
  • 44.
    Spring REST Docs •Documentation is built from tests • Supports hypermedia (HATEOAS) APIs • Immediate reaction to API changes • Keeps your code clean • Produces AsciiDoc snippets
  • 45.
    Basic Spring MVCTest @Test public void testGetAllPlanets() throws Exception { mockMvc.perform(get("/planets").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()",is(2))); }
  • 46.
    With Spring RESTDoc @Test public void testGetAllPlanets() throws Exception { mockMvc.perform(get("/planets").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()",is(2))) .andDo(document("planets/get")); }
  • 47.
    AsciiDoc snippets |=== |Path|Type|Description |`id` |`Number` |The idof the planet |`name` |`String` |The name of the planet |`diameter` |`Number` |The diameter of the planet |===
  • 48.
    AsciiDoc Plain-text writing format.AsciiDoc documents can be translated into various formats, including HTML, DocBook, PDF and ePub. = Hello, DevCon! Jeroen Reijn <jeroen.reijn@luminis.eu> An introduction to documenting Hypermedia APIs with https://projects.spring.io/spring-restdocs/[Spring REST Docs]. == First Section * item 1 * item 2
  • 49.
  • 50.
  • 51.
    Spring Auto RESTDocs • Extension for Spring REST Docs • Response field documentation generated by means of introspection • Partial support for documenting Hypermedia ‘links’ out of the box • DRY - Uses JavaDoc for generating documentation
  • 52.
    Spring REST Docsadvantages • Ability to focus on domain model rather than URI’s • ‘Guarantees’ that API documentation and implementation code are in-sync • Forces you to update documentation for any implementation changes • Ability to document with different payloads and explain different test scenarios • Ability to document remote APIs (with WebTestClient)
  • 53.
    In retrospect • DocumentingHypermedia API is getting easier • Validating APIs against their documentation is still ‘hard’ • Spring REST Docs can help documenting and validating the API • Good documentation is key to working with an API
  • 54.
    Those who standfor nothing, fall for anything - Alexander Hamilton ?Thank you Questions? is powered by Don’t forget to vote!