0% found this document useful (0 votes)
177 views

Spring Rest Api Documenting

This document provides details on using Spring REST Docs to document APIs, including documenting hypermedia links, request and response payloads, and fields within payloads. It describes how to configure Spring REST Docs to generate documentation snippets for links, requests, and responses. It also covers ignoring common links, documenting subsets of payloads, and relaxing requirements to avoid test failures when only documenting a subset of information.

Uploaded by

Groza Cristi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views

Spring Rest Api Documenting

This document provides details on using Spring REST Docs to document APIs, including documenting hypermedia links, request and response payloads, and fields within payloads. It describes how to configure Spring REST Docs to generate documentation snippets for links, requests, and responses. It also covers ignoring common links, documenting subsets of payloads, and relaxing requirements to avoid test failures when only documenting a subset of information.

Uploaded by

Groza Cristi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Spring REST Docs 05.07.

2021, 21:56

Documenting your API


This section provides more details about using Spring REST Docs to document your API.

Hypermedia
Spring REST Docs provides support for documenting the links in a hypermedia-based
(https://en.wikipedia.org/wiki/HATEOAS) API. The following examples show how to use it:

MockMvc WebTestClient REST Assured


JAVA
tthhiiss.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("index", links( 1
linkWithRel("alpha").description("Link to the alpha resource"), 2
linkWithRel("bravo").description("Link to the bravo resource")))); 3

1 Configure Spring REST docs to produce a snippet describing the response’s links. Uses the static
links method on org.springframework.restdocs.hypermedia.HypermediaDocumentation .

2 Expect a link whose rel is alpha . Uses the static linkWithRel method on
org.springframework.restdocs.hypermedia.HypermediaDocumentation .

3 Expect a link whose rel is bravo .

The result is a snippet named links.adoc that contains a table describing the resource’s links.

If a link in the response has a title , you can omit the description from its descriptor and

! the title is used. If you omit the description and the link does not have a title , a failure
occurs.

When documenting links, the test fails if an undocumented link is found in the response. Similarly, the test also
fails if a documented link is not found in the response and the link has not been marked as optional.

If you do not want to document a link, you can mark it as ignored. Doing so prevents it from appearing in the
generated snippet while avoiding the failure described above.

You can also document links in a relaxed mode, where any undocumented links do not cause a test failure. To
do so, use the relaxedLinks method on
org.springframework.restdocs.hypermedia.HypermediaDocumentation . This can be useful when
documenting a particular scenario where you only want to focus on a subset of the links.

Hypermedia Link Formats


Two link formats are understood by default:

Atom: Links are expected to be in an array named links . This is used by default when the content type of
the response is compatible with application/json .

https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/ Page 15 of 47
Spring REST Docs 05.07.2021, 21:56

HAL: Links are expected to be in a map named _links . This is used by default when the content type of the
response is compatible with application/hal+json .

If you use Atom- or HAL-format links but with a different content type, you can provide one of the built-in
LinkExtractor implementations to links . The following examples show how to do so:

MockMvc WebTestClient REST Assured


JAVA
.andDo(document("index", links(halLinks(), 1
linkWithRel("alpha").description("Link to the alpha resource"),
linkWithRel("bravo").description("Link to the bravo resource"))));

1 Indicate that the links are in HAL format. Uses the static halLinks method on
org.springframework.restdocs.hypermedia.HypermediaDocumentation .

If your API represents its links in a format other than Atom or HAL, you can provide your own implementation
of the LinkExtractor interface to extract the links from the response.

Ignoring Common Links


Rather than documenting links that are common to every response, such as self and curies when using
HAL, you may want to document them once in an overview section and then ignore them in the rest of your
API’s documentation. To do so, you can build on the support for reusing snippets to add link descriptors to a
snippet that is preconfigured to ignore certain links. The following example shows how to do so:

JAVA
ppuubblli cc s ttaat iicc LinksSnippet l iin k ss(LinkDescriptor... descriptors) {
rreet uurrn HypermediaDocumentation.links(linkWithRel("self").ignored().optional(),
linkWithRel("curies").ignored()).and(descriptors);
}

Request and Response Payloads


In addition to the hypermedia-specific support described earlier, support for general documentation of request
and response payloads is also provided.

By default, Spring REST Docs automatically generates snippets for the body of the request and the body of the
response. These snippets are named request-body.adoc and response-body.adoc respectively.

Request and Response Fields


To provide more detailed documentation of a request or response payload, support for documenting the
payload’s fields is provided.

Consider the following payload:

https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/ Page 16 of 47
Spring REST Docs 05.07.2021, 21:56

JSON
{
"contact": {
"name": "Jane Doe",
"email": "[email protected]"
}
}

You can document the previous example’s fields as follows:

MockMvc WebTestClient REST Assured


JAVA
tthhiiss.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("index",
responseFields( 1
fieldWithPath("contact.email")
.description("The user's email address"), 2
fieldWithPath("contact.name").description("The user's name")))); 3

1 Configure Spring REST docs to produce a snippet describing the fields in the response payload. To
document a request, you can use requestFields . Both are static methods on
org.springframework.restdocs.payload.PayloadDocumentation .

2 Expect a field with the path contact.email . Uses the static fieldWithPath method on
org.springframework.restdocs.payload.PayloadDocumentation .

3 Expect a field with the path contact.name .

The result is a snippet that contains a table describing the fields. For requests, this snippet is named request-
fields.adoc . For responses, this snippet is named response-fields.adoc .

When documenting fields, the test fails if an undocumented field is found in the payload. Similarly, the test also
fails if a documented field is not found in the payload and the field has not been marked as optional.

If you do not want to provide detailed documentation for all of the fields, an entire subsection of a payload can
be documented. The following examples show how to do so:

MockMvc WebTestClient REST Assured


JAVA
tthhiiss.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("index",
responseFields( 1
subsectionWithPath("contact")
.description("The user's contact details")))); 1

1 Document the subsection with the path contact . contact.email and contact.name are now

https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/ Page 17 of 47
Spring REST Docs 05.07.2021, 21:56

seen as having also been documented. Uses the static subsectionWithPath method on
org.springframework.restdocs.payload.PayloadDocumentation .

subsectionWithPath can be useful for providing a high-level overview of a particular section of a payload.
You can then produce separate, more detailed documentation for a subsection. See Documenting a Subsection
of a Request or Response Payload.

If you do not want to document a field or subsection at all, you can mark it as ignored. This prevents it from
appearing in the generated snippet while avoiding the failure described earlier.

You can also document fields in a relaxed mode, where any undocumented fields do not cause a test failure. To
do so, use the relaxedRequestFields and relaxedResponseFields methods on
org.springframework.restdocs.payload.PayloadDocumentation . This can be useful when documenting a
particular scenario where you want to focus only on a subset of the payload.

By default, Spring REST Docs assumes that the payload you are documenting is JSON. If you

! want to document an XML payload, the content type of the request or response must be
compatible with application/xml .

Fields in JSON Payloads


This section describes how to work with fields in JSON payloads.

JSON Field Paths


JSON field paths use either dot notation or bracket notation. Dot notation uses '.' to separate each key in the
path (for example, a.b ). Bracket notation wraps each key in square brackets and single quotation marks (for
example, ['a']['b'] ). In either case, [] is used to identify an array. Dot notation is more concise, but using
bracket notation enables the use of . within a key name (for example, ['a.b'] ). The two different notations
can be used in the same path (for example, a['b'] ).

Consider the following JSON payload:

JSON
{
"a":{
"b":[
{
"c":"one"
},
{
"c":"two"
},
{
"d":"three"
}
],
"e.dot" : "four"
}
}

https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/ Page 18 of 47
Spring REST Docs 05.07.2021, 21:56

In the preceding JSON payload, the following paths are all present:

Path Value

a An object containing b

a.b An array containing three objects

['a']['b'] An array containing three objects

a['b'] An array containing three objects

['a'].b An array containing three objects

a.b[] An array containing three objects

a.b[].c An array containing the strings one and two

a.b[].d The string three

a['e.dot'] The string four

['a']['e.dot'] The string four

You can also document a payload that uses an array at its root. The path [] refers to the entire array. You can
then use bracket or dot notation to identify fields within the array’s entries. For example, [].id corresponds
to the id field of every object found in the following array:

JSON
[
{
"id":1
},
{
"id":2
}
]

You can use * as a wildcard to match fields with different names. For example, users.*.role could be used
to document the role of every user in the following JSON:

https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/ Page 19 of 47
Spring REST Docs 05.07.2021, 21:56

JSON
{
"users":{
"ab12cd34":{
"role": "Administrator"
},
"12ab34cd":{
"role": "Guest"
}
}
}

JSON Field Types


When a field is documented, Spring REST Docs tries to determine its type by examining the payload. Seven
different types are supported:

Type Description

array The value of each occurrence of the field is an array.

boolean The value of each occurrence of the field is a boolean ( true or false ).

object The value of each occurrence of the field is an object.

number The value of each occurrence of the field is a number.

null The value of each occurrence of the field is null.

string The value of each occurrence of the field is a string.

varies The field occurs multiple times in the payload with a variety of different types.

You can also explicitly set the type by using the type(Object) method on FieldDescriptor . The result of the
toString method of the supplied Object is used in the documentation. Typically, one of the values
enumerated by JsonFieldType is used. The following examples show how to do so:

MockMvc WebTestClient REST Assured


JAVA
.andDo(document("index",
responseFields(
fieldWithPath("contact.email").type(JsonFieldType.STRING) 1
.description("The user's email address"))));

1 Set the field’s type to String .

XML payloads
This section describes how to work with XML payloads.

https://docs.spring.io/spring-restdocs/docs/2.0.5.RELEASE/reference/html5/ Page 20 of 47

You might also like