Skip to content

Adding Examples for REST APIs

Malintha Amarasinghe edited this page Jul 18, 2019 · 8 revisions

Overview

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:

  1. Avoid making the REST API definition unnecessarily longer due to examples.
  2. Supporting multiple examples per operation.
  3. Reuse examples in the test cases (for mocking API calls).

How to add an example

Let's say you need to add a sample for GET /apis request.

  1. Create the example file

Example files are located in below paths:

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

Add a file (with a folder if necessary) to include the examples.

image

  1. Example file structure
- 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