-
Notifications
You must be signed in to change notification settings - Fork 637
Adding Examples for REST APIs
In APIM 3.0.0 onwards, the format of defining REST API examples is changed. Instead of using inline samples using x-wso2-request
, x-wso2-response
elements, the examples are decomposed from the main swagger and added as separate files. The files are linked to the OpenAPI definition with x-example
element with the relative path of the example files.
The approach has below advantages:
- Avoid making the REST API definition unnecessarily longer due to examples.
- Supporting multiple examples per operation.
- Reuse examples in the test cases (for mocking API calls).
- id: [ id of the 1st example.]
request:
method: [ request method ]
url: [ request url ]
headers: |
[ request headers ]
response:
status:
code: [ response status code ]
msg: [ response status message ]
headers: |
[ response headers ]
body:
[ response body ]
- id: [ id of the 2nd example.]
request:
method: ...
url: ...
headers: |
...
response:
...
Note:
- Every example is an array item. Note the starting
-
. -
headers
element is a multiline string. Not an array. - Use a unique
id
to represent the example. It needs to be unique with the examples defined in the same file.id
can be used to retrieve the example when writing React unit tests. For more information see: Mocking REST APIs for React Unit Tests
Publisher:
carbon-apimgt/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/docs/examples
Store:
carbon-apimgt/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/docs/examples
Let's say you need to add a sample for GET /apis
request.
- Create the example file
Add a file (with a folder if necessary) to include the examples.
Eg: apis/apis_get.yaml
- id: getAllAPIsSimple
request:
method: GET
url: https://localhost:9443/api/am/publisher/v1.0/apis
headers: |
Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8
response:
status:
code: 200
msg: OK
headers: |
Content-Type: application/json
body:
{
"count": 1,
"list": [
{
"id": "ae4eae22-3f65-387b-2323-d37eaa366fa8",
"name": "CalculatorAPI",
"description": "A calculator API that supports basic operations",
"context": "CalculatorAPI",
"version": "1.0.0",
"provider": "admin",
"lifeCycleStatus": "CREATED",
"workflowStatus": "APPROVED",
"hasThumbnail": true,
"securityScheme": [
"oauth2"
]
}
],
"pagination": {
"offset": 0,
"limit": 1,
"total": 1,
"next": "",
"previous": ""
}
}
- Link the sample to the OpenAPI definition
Use the relative path of the example file with x-examples
extension.
x-examples:
$ref: docs/examples/apis/apis_get.yaml
- Build the REST API component to generate documentation
Do an mvn clean install
in the REST API component. This will generate documentation in the docs
folder in the carbon-apimgt
root location with the new example you added.