Test-Driven Documentation for your REST(ful) service

Jeroen Reijn
Jeroen ReijnSoftware/Solution Architect at Luminis
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
Test-Driven Documentation for your REST(ful) service
API Blueprint / Apiary
• Markdown flavoured syntax
• Powerful designer UI
• Documentation while designing
• Java code generator support is *very* minimal
Test-Driven Documentation for your REST(ful) service
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
Test-Driven Documentation for your REST(ful) service
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
Test-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) service
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
Test-Driven Documentation for your REST(ful) service
“ An API is only as good 

as its documentation! ”
Let’s talk about API documentation
Test-Driven Documentation for your REST(ful) service
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);
Test-Driven Documentation for your REST(ful) service
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!
1 of 54

Recommended

Nordic APIs - Automatic Testing of (RESTful) API Documentation by
Nordic APIs - Automatic Testing of (RESTful) API DocumentationNordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API DocumentationRouven Weßling
235 views26 slides
An afternoon with angular 2 by
An afternoon with angular 2An afternoon with angular 2
An afternoon with angular 2Mike Melusky
435 views42 slides
Getting Started With Angular by
Getting Started With AngularGetting Started With Angular
Getting Started With AngularStormpath
756 views42 slides
Building an API using Grape by
Building an API using GrapeBuilding an API using Grape
Building an API using Grapevisnu priya
1.1K views14 slides
Angular2 Development for Java developers by
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developersYakov Fain
3.9K views66 slides
Consuming REST services with ActiveResource by
Consuming REST services with ActiveResourceConsuming REST services with ActiveResource
Consuming REST services with ActiveResourceWolfram Arnold
5.5K views23 slides

More Related Content

What's hot

WinAppDriver Development by
WinAppDriver DevelopmentWinAppDriver Development
WinAppDriver DevelopmentJeremy Kao
2K views14 slides
Angular 4 for Java Developers by
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java DevelopersYakov Fain
7.3K views40 slides
PyUIA 0.3 by
PyUIA 0.3PyUIA 0.3
PyUIA 0.3Jeremy Kao
958 views26 slides
Laravel 5 and SOLID by
Laravel 5 and SOLIDLaravel 5 and SOLID
Laravel 5 and SOLIDIgor Talevski
10.2K views37 slides
SETCON'18 - Ilya labacheuski - GraphQL adventures by
SETCON'18 - Ilya labacheuski - GraphQL adventuresSETCON'18 - Ilya labacheuski - GraphQL adventures
SETCON'18 - Ilya labacheuski - GraphQL adventuresNadzeya Pus
43 views60 slides
[2015/2016] JavaScript by
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScriptIvano Malavolta
717 views86 slides

What's hot(20)

WinAppDriver Development by Jeremy Kao
WinAppDriver DevelopmentWinAppDriver Development
WinAppDriver Development
Jeremy Kao2K views
Angular 4 for Java Developers by Yakov Fain
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
Yakov Fain7.3K views
Laravel 5 and SOLID by Igor Talevski
Laravel 5 and SOLIDLaravel 5 and SOLID
Laravel 5 and SOLID
Igor Talevski10.2K views
SETCON'18 - Ilya labacheuski - GraphQL adventures by Nadzeya Pus
SETCON'18 - Ilya labacheuski - GraphQL adventuresSETCON'18 - Ilya labacheuski - GraphQL adventures
SETCON'18 - Ilya labacheuski - GraphQL adventures
Nadzeya Pus43 views
Modern Tools for API Testing, Debugging and Monitoring by Neil Mansilla
Modern Tools for API Testing, Debugging and MonitoringModern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and Monitoring
Neil Mansilla8.6K views
Introduction to React Native by Polidea
Introduction to React NativeIntroduction to React Native
Introduction to React Native
Polidea2.5K views
Exploring Angular 2 - Episode 1 by Ahmed Moawad
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1
Ahmed Moawad681 views
React Native custom components by Jeremy Grancher
React Native custom componentsReact Native custom components
React Native custom components
Jeremy Grancher5.3K views
Scala Italy 2015 - Hands On ScalaJS by Alberto Paro
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
Alberto Paro1.2K views
OpenAPI development with Python by Takuro Wada
OpenAPI development with PythonOpenAPI development with Python
OpenAPI development with Python
Takuro Wada31.6K views
Having fun with code igniter by Ahmad Arif
Having fun with code igniterHaving fun with code igniter
Having fun with code igniter
Ahmad Arif378 views
Introduction to React Native by Rami Sayar
Introduction to React NativeIntroduction to React Native
Introduction to React Native
Rami Sayar2.2K views
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine by Roman Kirillov
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Roman Kirillov6.8K views
GraphQL in an Age of REST by Yos Riady
GraphQL in an Age of RESTGraphQL in an Age of REST
GraphQL in an Age of REST
Yos Riady829 views

Similar to Test-Driven Documentation for your REST(ful) service

API workshop: Introduction to APIs (TC Camp) by
API workshop: Introduction to APIs (TC Camp)API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)Tom Johnson
3.2K views51 slides
Play Support in Cloud Foundry by
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundryrajdeep
1.5K views39 slides
Building Better Web APIs with Rails by
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with RailsAll Things Open
1.4K views58 slides
Entity provider selection confusion attacks in JAX-RS applications by
Entity provider selection confusion attacks in JAX-RS applicationsEntity provider selection confusion attacks in JAX-RS applications
Entity provider selection confusion attacks in JAX-RS applicationsMikhail Egorov
1.7K views23 slides
Graphql usage by
Graphql usageGraphql usage
Graphql usageValentin Buryakov
413 views37 slides
Andrei shakirin rest_cxf by
Andrei shakirin rest_cxfAndrei shakirin rest_cxf
Andrei shakirin rest_cxfAravindharamanan S
246 views59 slides

Similar to Test-Driven Documentation for your REST(ful) service(20)

API workshop: Introduction to APIs (TC Camp) by Tom Johnson
API workshop: Introduction to APIs (TC Camp)API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)
Tom Johnson3.2K views
Play Support in Cloud Foundry by rajdeep
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
rajdeep1.5K views
Building Better Web APIs with Rails by All Things Open
Building Better Web APIs with RailsBuilding Better Web APIs with Rails
Building Better Web APIs with Rails
All Things Open1.4K views
Entity provider selection confusion attacks in JAX-RS applications by Mikhail Egorov
Entity provider selection confusion attacks in JAX-RS applicationsEntity provider selection confusion attacks in JAX-RS applications
Entity provider selection confusion attacks in JAX-RS applications
Mikhail Egorov1.7K views
SharePoint 2013 APIs by John Calvert
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIs
John Calvert1.2K views
GraphQL: The Missing Link Between Frontend and Backend Devs by Sashko Stubailo
GraphQL: The Missing Link Between Frontend and Backend DevsGraphQL: The Missing Link Between Frontend and Backend Devs
GraphQL: The Missing Link Between Frontend and Backend Devs
Sashko Stubailo4K views
Angular for Java Enterprise Developers: Oracle Code One 2018 by Loiane Groner
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
Loiane Groner726 views
Survival Strategies for API Documentation: Presentation to Southwestern Ontar... by Tom Johnson
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Survival Strategies for API Documentation: Presentation to Southwestern Ontar...
Tom Johnson2.3K views
Spring Web Services: SOAP vs. REST by Sam Brannen
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen22.4K views
Intro to node.js - Ran Mizrahi (27/8/2014) by Ran Mizrahi
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
Ran Mizrahi1.1K views
Intro to node.js - Ran Mizrahi (28/8/14) by Ran Mizrahi
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi564 views
Ibm_interconnect_restapi_workshop by Shubhra Kar
Ibm_interconnect_restapi_workshopIbm_interconnect_restapi_workshop
Ibm_interconnect_restapi_workshop
Shubhra Kar673 views
Sinergija2012 - Developing REST API for Windows Azure with ASP.NET Web API by Radenko Zec
Sinergija2012 - Developing REST API for Windows Azure with ASP.NET Web APISinergija2012 - Developing REST API for Windows Azure with ASP.NET Web API
Sinergija2012 - Developing REST API for Windows Azure with ASP.NET Web API
Radenko Zec488 views
Building APIs in an easy way using API Platform by Antonio Peric-Mazar
Building APIs in an easy way using API PlatformBuilding APIs in an easy way using API Platform
Building APIs in an easy way using API Platform
Antonio Peric-Mazar2.6K views
ASP.NET Core 1.0 by Ido Flatow
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
Ido Flatow701 views

More from Jeroen Reijn

Hoe releasen minder pijnlijk werd bij de ANWB Alarmcentrale by
Hoe releasen minder pijnlijk werd bij de ANWB AlarmcentraleHoe releasen minder pijnlijk werd bij de ANWB Alarmcentrale
Hoe releasen minder pijnlijk werd bij de ANWB AlarmcentraleJeroen Reijn
381 views64 slides
Continuous Delivery in a content centric world by
Continuous Delivery in a content centric worldContinuous Delivery in a content centric world
Continuous Delivery in a content centric worldJeroen Reijn
483 views39 slides
Hippo CMS Integration Patterns by
Hippo CMS Integration PatternsHippo CMS Integration Patterns
Hippo CMS Integration PatternsJeroen Reijn
2.8K views19 slides
Real-time visitor analysis with Couchbase and Elastichsearch by
Real-time visitor analysis with Couchbase and ElastichsearchReal-time visitor analysis with Couchbase and Elastichsearch
Real-time visitor analysis with Couchbase and ElastichsearchJeroen Reijn
3.7K views46 slides
Shootout! Template engines for the JVM by
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVMJeroen Reijn
80.2K views44 slides
Hippo GetTogether: The architecture behind Hippos relevance platform by
Hippo GetTogether: The architecture behind Hippos relevance platformHippo GetTogether: The architecture behind Hippos relevance platform
Hippo GetTogether: The architecture behind Hippos relevance platformJeroen Reijn
2.5K views53 slides

More from Jeroen Reijn(8)

Hoe releasen minder pijnlijk werd bij de ANWB Alarmcentrale by Jeroen Reijn
Hoe releasen minder pijnlijk werd bij de ANWB AlarmcentraleHoe releasen minder pijnlijk werd bij de ANWB Alarmcentrale
Hoe releasen minder pijnlijk werd bij de ANWB Alarmcentrale
Jeroen Reijn381 views
Continuous Delivery in a content centric world by Jeroen Reijn
Continuous Delivery in a content centric worldContinuous Delivery in a content centric world
Continuous Delivery in a content centric world
Jeroen Reijn483 views
Hippo CMS Integration Patterns by Jeroen Reijn
Hippo CMS Integration PatternsHippo CMS Integration Patterns
Hippo CMS Integration Patterns
Jeroen Reijn2.8K views
Real-time visitor analysis with Couchbase and Elastichsearch by Jeroen Reijn
Real-time visitor analysis with Couchbase and ElastichsearchReal-time visitor analysis with Couchbase and Elastichsearch
Real-time visitor analysis with Couchbase and Elastichsearch
Jeroen Reijn3.7K views
Shootout! Template engines for the JVM by Jeroen Reijn
Shootout! Template engines for the JVMShootout! Template engines for the JVM
Shootout! Template engines for the JVM
Jeroen Reijn80.2K views
Hippo GetTogether: The architecture behind Hippos relevance platform by Jeroen Reijn
Hippo GetTogether: The architecture behind Hippos relevance platformHippo GetTogether: The architecture behind Hippos relevance platform
Hippo GetTogether: The architecture behind Hippos relevance platform
Jeroen Reijn2.5K views
Building a relevance platform with Couchbase and Elasticsearch by Jeroen Reijn
Building a relevance platform with Couchbase and ElasticsearchBuilding a relevance platform with Couchbase and Elasticsearch
Building a relevance platform with Couchbase and Elasticsearch
Jeroen Reijn2.5K views
Basic web application development with Apache Cocoon 2.1 by Jeroen Reijn
Basic web application development with  Apache Cocoon 2.1Basic web application development with  Apache Cocoon 2.1
Basic web application development with Apache Cocoon 2.1
Jeroen Reijn2.7K views

Recently uploaded

Navigating container technology for enhanced security by Niklas Saari by
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas SaariMetosin Oy
14 views34 slides
The Era of Large Language Models.pptx by
The Era of Large Language Models.pptxThe Era of Large Language Models.pptx
The Era of Large Language Models.pptxAbdulVahedShaik
6 views9 slides
SAP FOR CONTRACT MANUFACTURING.pdf by
SAP FOR CONTRACT MANUFACTURING.pdfSAP FOR CONTRACT MANUFACTURING.pdf
SAP FOR CONTRACT MANUFACTURING.pdfVirendra Rai, PMP
13 views2 slides
Generic or specific? Making sensible software design decisions by
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
6 views60 slides
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...Deltares
14 views23 slides
SAP FOR TYRE INDUSTRY.pdf by
SAP FOR TYRE INDUSTRY.pdfSAP FOR TYRE INDUSTRY.pdf
SAP FOR TYRE INDUSTRY.pdfVirendra Rai, PMP
24 views3 slides

Recently uploaded(20)

Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares14 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
Advanced API Mocking Techniques by Dimpy Adhikary
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking Techniques
Dimpy Adhikary19 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor8 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8712 views
SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor23 views
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft... by Deltares
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
DSD-INT 2023 Process-based modelling of salt marsh development coupling Delft...
Deltares7 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri860 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta6 views

Test-Driven Documentation for your REST(ful) service

  • 1. Test-Driven Documentation for your RESTful service by Jeroen Reijn
  • 2. 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
  • 5. Streaming 1% RPC 10% REST 89% REST RPC Streaming GraphQL source: https://www.programmableweb.com/
  • 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 in resource 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" } } }
  • 14. Let’s talk about API design
  • 19. 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
  • 21. API Blueprint / Apiary • Markdown flavoured syntax • Powerful designer UI • Documentation while designing • Java code generator support is *very* minimal
  • 23. 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
  • 25. 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)
  • 26. Swagger • Tools around the OpenAPI specification • Swagger editor • Swagger-UI • Swagger Codegen (server and client libs and many languages) • Swagger Inspector
  • 29. 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; }
  • 30. 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
  • 33. “ An API is only as good 
 as its documentation! ”
  • 34. Let’s talk about API documentation
  • 37. Documentation based on specs HTML / PDF
  • 38. Docs based on code @GetMapping(value = "/films/{id}") ResponseEntity<Film> getFilmById(@PathVariable(“id") String id);
  • 39. 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);
  • 41. 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
  • 42. “ API documentation needs to be more then just endpoints and resources ”
  • 43. Spring REST Docs “Document RESTful 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 MVC Test @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 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")); }
  • 47. 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 |===
  • 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
  • 51. 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
  • 52. 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)
  • 53. 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
  • 54. Those who stand for nothing, fall for anything - Alexander Hamilton ?Thank you Questions? is powered by Don’t forget to vote!