Response Stubbing/Mocking

Overview

With respect to the payload they return, API response stubs/mocks are canned responses - responses that don’t change between requests for the same simlet.

Here is how to define in simlet.yaml that a response comes from a stub:

response:
  from: stub

Response Status

The following configures status code 200 (OK) for a response:

response:
  from: stub
  status: 200

Another way to define the HTTP status is to use the following form, which allows one to specify the status code and the reason as well, including custom, non-standard values:

response:
  from: stub
  status:
    code: 200
    reason: OK

API Simulator will actually default the HTTP status to 200 (OK) if the status isn’t configured. However, it is regarded as a better practice to configure explicitly the HTTP status to avoid confusion and unexpected results.

See also here for how to dynamically configure the status code using a placeholder or scriptlet.

HTTP Protocol Version

Use httpVersion to configure the HTTP protocol version. If not specified, it will default to "HTTP/1.1":

response:
  from: stub
  httpVersion: "HTTP/1.0"
  status: 200

Configuring httpVersion has no effect for HTTP/2.

Header Fields

Use the headers property to define a list of response header fields:

response:
  from: stub
  status: 200

  # List of headers.
  # - The order of the header fields is preserved.
  # - Any whitespaces are preserved.
  # - Duplicate elements for the same header name are allowed (just like per the HTTP spec).
  headers:
    # Verbatim header. API Simulator will add '\r\n' as EOL (end-of-line) delimiter
  - "Content-Type: application/json; charset=UTF-8"
    # Alternative header field definition
  - name: "Connection"
    value: "close"

If the list of headers contains Date header definition then API Simulator will use it. Otherwise, API Simulator by default will add "Date" header with the current datetime formatted according to the HTTP specification.

Similarly for the Server header - API Simulator will add it automatically, if not present, and set its value to the API Simulator’s version.

Body

Use the body property to configure the body of a HTTP response. The body can be one of two types - text or binary:

response:
  from: stub
  ...
  body:
    type: text | binary

Each body type has different options to choose from and to configure.

Text Body Content

response:
  from: stub
  ...
  body:
    # The type is assumed to be 'text' if not specified
    type: text
    # Optional charset. Defaults to UTF-8
    charset: UTF-8
    # Specify body content as value of a 'text' element when there is charset configuration
    text: <body content here>

The following is a shorter configuration equivalent to the one above - it is applicable when the body type is text and the charset is the default UTF-8:

response:
  from: stub
  ...
  body: <body content here>

Multi-line body content can be configured in different ways. Since v1.7 API Simulator extends the YAML syntax and supports multi-line text surrounded by a pair of backtick characters, similar to template literals in JavaScript - `....` (the backtick character is usually found on the same keyboard key as tilde ~, above the Tab):

response:
  from: stub
  ...
  body: `
{
   "results" : [
      {
         "formatted_address" : "100 Pineapple Pkwy, Alta Vista, CA",
         "location" : {
            "lat" : 34.7223607,
            "lng" : -102.2841964
         },
         "place_id" : "Ch0J2eUgeAK6j4ARbn5u_wAGqWA"
      }
   ],
   "status" : "OK"
}`

Using this syntax, you don’t have to worry about indentation. Consider that:

  • The text between the backtick characters is taken verbatim, including any leading spaces on each line.

  • End of lines between the backtick characters do not need to be escaped and they are included in the text; other special characters are not escaped.

  • The multi-line text must start on a new line after the opening backtick character.

  • The closing backtick character could be on a new line after the end of the text, in which case a new line will be included in the text, or it can immediately follow the last character of the text.

  • This also works anywhere a single-line single-quoted string ('....'), single-line double-quoted string ("...."), or a multi-line text that follows a chomping indicator is accepted.

  • The fields that follow a backtick-surrounded text must have the proper indentation according to their level.

If escaping special characters is needed or you are used to the YAML syntax, use a chomping indicator per the YAML standard followed by the properly indented multi-line text. For example (notice the indentation of the opening { and closing } curly brackets and the rest of the body content between them):

response:
  from: stub
  ...
  body: |-
    {
       "results" : [
          {
             "formatted_address" : "100 Pineapple Pkwy, Alta Vista, CA",
             "location" : {
                "lat" : 34.7223607,
                "lng" : -102.2841964
             },
             "place_id" : "Ch0J2eUgeAK6j4ARbn5u_wAGqWA"
          }
       ],
       "status" : "OK"
    }

Text Body Content From a File

The content of a static text body can also come from an external file:

response:
  from: stub
  status: 200
  headers:
  - "Content-Type: application/json"
  body:
    # implied type text
    # type: text
    file: "${simlet.path}/place-100-Pineapple-Pkwy.json"

In the example above, ${simlet.path} is a global variable for the directory were the simlet is defined. There is two other global variables - ${sim.path} and ${simlets.path} - that resolves to the simulation directory and the "simlets" directory and can also be used to represent paths to files.

Binary Body Content

Stubbed responses could return binary content in the body like images, for example. API Simulator offers two ways to configure binary body content for a response: as a base64-encoded string in the simlet.yaml configuration file or as an external file.

Base64-Encoded Body Content

response:
  from: stub
  status: 200
  headers:
  - "Content-Type: image/png"
  body:
    type: binary
    base64: `
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAALGPC/xhBQAAACBjSFJN
AAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACuFBMVEUAAABBlohlsaePkLpY
u3QrjHViop0j78aDv8lcupZX+f7XtaloyK5W26y5+Pl94cl62M5j18Rj28f///+bIP9GjTmYyJtA
lIZKqZ5TsKBqractm3kunX01r4Q+q4JCoICCorlEvX9CtZI0sY04rINOt6BpwsMtqW8wpYAwqIlL
r55Tr5Jg0rYihE4kkWA8pV5Hs3ha0rFW0LMlYzwhdEdT169d37MkaTwgYztb3raL4dMim1QieUFc
1rZ52M4nn1kieUBWy7Nl2cYjlz4gcTBv2MoniUIiZC1zzspc1NclczkiWCp7z8Wb4eAgTCQiRCJk
spyQ0cYsSx8tTSIuckJKlG9FaSpFZytFZS1GYi9GZDFFZTFGZTBHZC9GYS5FXSxDWilBVyZBbDBQ
llNjeDBcbi5XbytacTFacjNYcTVYbjRabzJebTJgai5eaSlaZilje0Gq5r4rpngvvH86xY0soHcp
rW8ttXk2uI1Bs50moXUkiF4ghFYjjFkpimwrhlczmVcknmofhEkcgkoeg1QmiFonlUg8sGBM0XBH
xmRLvIsnn2QfgEEkiFUdcEgicEEmcjgqSDVImmNP1HRIsXBKw5ctn2EidT4ngEwjaEQjUzwmSys3
XEM5lFQ8uWBDpnBEroYonlkcdTcigkUkckIiRDEhMSUlQCooeTsvi004j2Q6onkwmlgwg1Ixfk82
hlsuYUUpPDQnNzMqVkYwdFk0k2lEpYd3zMYqcDlFgF88cU87aks/d1tBdl1Me2lLjHRIpYVMs5ZU
qJl4wr8mWigoWiwhUycbSiEfUSQmXjAwcEU7hFtAkmpNoIJTqZBguaUpSiQuWCcwWygvWSguWSou
XywuYS8uZTcsbz8udUwtdlU4iWwxUyczUyk2Vio2Vyk1VSg3Vig3VCg1UigzUigwViwoXDD///9n
BdOpAAAAcnRSTlMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmDeh5p/v64MAIKKcPkhidA2f3VUwtI
9PS4ditI9Nk2SPSqCEj05idI9PZDSPSBSPSsBEj0zhhI9NIcSPTmVzW90dro9Pn4+fj18tpZAxAY
IzhTZWRtcl1LKQMTLq6JAAAAAWJLR0QTDLtclgAAAAd0SU1FB+AKCRYTMLK1SPUAAAEQSURBVBjT
Y2BgFJeQlGJiZoABFlZpGVk5eQU2mICiknJRcYmKqho7B0RAXUOztKy8olJLW4eTCySgq1dVXVNb
V9+gb2BoxM3DwGBs0tjU3NLa1t7R2WVqxsvHYG7R3dPb1z9h4qTJU6ZaWvEzWNtMmz5j5qzZc+bO
m7/A1k6Awd5h4aLFS5YuW75i5arVjk6CDM4ua9auW79h46bNW7Zu2+4qxODmvmPnrt179u7bf+Dg
ocMengxe3keOHjt+4uSp02fOnjvv48vg53/h4qXLV65eu37j5q3bAYEMQcF37t67/+Dho8dPnj4L
CRVmCAuPiIyKjomNi09ITEoWEWVISU1Lz8jMys7JzcsvKBRjAADW5mfGjYyYUwAAACV0RVh0ZGF0
ZTpjcmVhdGUAMjAxNi0xMC0wOVQyMjoxOTo0OCswMjowMBGRPS0AAAAldEVYdGRhdGU6bW9kaWZ5
ADIwMTYtMTAtMDlUMjI6MTk6NDgrMDI6MDBgzIWRAAAAV3pUWHRSYXcgcHJvZmlsZSB0eXBlIGlw
dGMAAHic4/IMCHFWKCjKT8vMSeVSAAMjCy5jCxMjE0uTFAMTIESANMNkAyOzVCDL2NTIxMzEHMQH
y4BIoEouAOoXEXTyQjWVAAAAAElFTkSuQmCC`

The base64-encoded string could be on a (long) single line, too, and without line breaks.

Notice that the base64-encoded text is surrounded by backtick characters. If we were to use a chomping indicator like |-, the lines should have all been properly indented.

Binary Body Content From a File

Assuming that an image file called favicon-16x16.png is in a directory called images under the directory for all simlets in a simulation, let’s configure HTTP response that will always return the content of the file:

response:
  from: stub
  status: 200
  headers:
  - "Content-Type: image/png"
  body:
    type: binary
    file: "${simlets.path}/images/favicon-16x16.png"

In the example above, ${simlets.path} is a global variable for the "simlets" directory were all simlets for the simulation reside. There are two other global variable - ${sim.path} and ${simlet.path} - that resolve respectively to the simulation directory and the directory where the simlet’s configuration was loaded from, and can also be used to represent paths to files.

Another option is to use provide the file specification as two values - path and name:

response:
  from: stub
  status: 200
  headers:
  - 'Content-Type: image/png'
  body:
    type: binary
    file:
      path: "${simlets.path}/images"
      name: "favicon-16x16.png"

Using the / delimiter works on Linux, Mac, and Windows.

Callback

See the Callback documentation for more information.


We would love to hear your feedback - send us a quick email to [feedback at APISimulator.com]

Happy API Simulating!