Then create a stub to handle posting of the first list item. When triggered this stub will move the scenario state to "First item added":
Finally, create a stub to return the list containing one item, which is matched only when the scenario is in the "First item added" state:
## Testing
First, make a `GET` request to fetch the list, which should be empty. You should be able to do this any number of times
without the result changing:
Under "State operations", click "Add operation":
For now, leave the Context as "Default context" and the Operation as `SET`. Add a Key called `itemName` with a value of
"Socks":
Under Response, check "Enable dynamic response templating" and put the following in the body text area:
```handlebars
State itemName was set to {{ state 'itemName' }}
```
Try making a `POST` to `/setAnItemName` - you should get a response with a body "State itemName was set to Socks".
You can now use the Handlebars helper `{{ state 'itemName' }}` in the Response body of any stub to return the state
value currently associated with the `itemName` key in the default context. For instance if you add a new stub for
`GET /someItemName`, check "Enable dynamic response templating" and put the following in the body
text area:
```handlebars
The current itemName is {{ state 'itemName' }}
```
then subsequent requests for that stub will return "The current itemName is Socks"
### Setting state dynamically
The "Value" field on a `SET` State operation supports Handlebars templating in order to dynamically set the value based
on the contents of an incoming request. The model available in the template is [the same request data model that is provided in the response template](/response-templating/basics/#the-data-model),
along with a `previousValue` containing the value of the Key in this Context before the operation was run, or `null` if
it had no value.
For example, we could change the "Value" in the example above to `{{ request.body }}`. Now the
`itemName` state key in the default context will be associated with the request body that was last sent as a `POST` to
`/setAnItemName`. For instance a `POST` to `/setAnItemName` with body "Shoes" will return "State itemName was set to
Shoes", and a subsequent `GET` to `/someItemName` will then return "The current itemName is Shoes".
While state values are stored as strings, it is normally convenient to make those strings valid JSON and use
[WireMock Cloud's rich set of JSON helpers](/response-templating/json) to manipulate those values using the template
in the "Value" field.
### Setting state in a context
When a value is assigned to a key, this value is confined to a particular context. That context can be defaulted for an
entire Mock API, and unless changed it is effectively a global context. When you render a value in a template using
`{{ state '
### State concurrency semantics
A Mock API can receive multiple concurrent requests. These may contain state operations that operate on a
`previousValue`; for instance you might store a `requestCount` state value, and make the SET operation increment it as
so: `{{math previousValue '+' 1}}`. WireMock Cloud guarantees that SET operations on a particular
Key in a particular Context will happen sequentially, so 5 concurrent requests to that stub would increment the
`requestCount` 5 times.
## Limits
You can read more about [plan limits here](./plan-limits/).
## Examples
* [An example of modelling a shopping basket with dynamic state](./basket-example/)
### Deployment
Source: https://docs.wiremock.io/concepts/deployment
## Deployment Modes
WireMock can be deployed in three distinct modes, each suited to different organizational needs and constraints:
1. **Cloud** - Fully managed hosting
2. **Self-hosted** - Complete on-premises deployment
3. **Hybrid** - Control plane in the cloud, data plane on-premises
## Cloud Deployment
With Cloud deployment, WireMock hosts everything for you:
- **Control plane** - The management interface and API
- **Data plane** - The mock API endpoints that respond to requests
- **User interface** - The web-based UI for managing your simulations
All components are accessible from the internet with nothing to install or maintain. This mode provides:
- Immediate availability with no infrastructure setup
- Automatic updates and maintenance
- Built-in scalability and high availability
- Public accessibility for remote teams and external integrations
Cloud deployment is ideal for:
- Quick prototyping and experimentation
- Teams without dedicated infrastructure
- Scenarios where public internet accessibility is acceptable
- Organizations wanting zero operational overhead
## Self-Hosted Deployment
Self-hosted deployment involves running the entire WireMock product stack on your own Kubernetes cluster.
This mode requires you to:
- Provide and manage a Kubernetes cluster
- Provide and manage a Postgres database
- Handle installation, updates, and maintenance
- Configure networking, DNS, certificates and security
- Monitor and scale infrastructure as needed
Self-hosted deployment offers:
- Complete control over data and infrastructure
- Ability to keep all traffic within private networks
- Customization of deployment topology
- Compliance with strict data residency requirements
This mode is appropriate for:
- Organizations with security policies prohibiting cloud services
- Scenarios requiring air-gapped or isolated network environments
- Teams with existing Kubernetes expertise and infrastructure
- Situations demanding complete data sovereignty
## Hybrid Deployment
[Hybrid deployment](/concepts/runner) balances convenience with control by splitting the architecture:
the control plane an UI remain in the cloud while API simulations are hosted in your infrastructure
using WireMock Runner.
Benefits of hybrid deployment:
- Simplified management through the cloud-hosted UI
- Data plane traffic stays within your network
- Flexibility to deploy mock APIs where they're needed
- Reduced operational burden compared to full self-hosting
Hybrid deployment suits:
- Development and testing workflows requiring local or private simulated APIs
- CI/CD pipelines that can't access public internet services
- Organizations comfortable with cloud management but requiring private data planes
- Scenarios needing simulated APIs in multiple diverse locations
### WireMock Runner
Source: https://docs.wiremock.io/concepts/runner
*This page explains concepts behind WireMock Runner. To start using the Runner right away, [follow the instructions here](/runner/overview)*
**WireMock Runner** runs as a service anywhere you want and enables you to record, to sync with Cloud, and to host mock APIs in your own infrastructure while continuing to use WireMock Cloud's management interface and collaboration features as a centralized control plane.
This hybrid mode splits the difference between Cloud-only and fully self-managed, letting you mix the benefits of Cloud with local development workflows and execution in your own private cloud infrastructure.
## What is WireMock Runner?
WireMock Runner is a long-running service packaged as a container that can be run anywhere you can deploy it. It connects to WireMock Cloud for configuration and collaboration, but executes recordngs and runs mock APIs locally in your environment, using the same [WireMock OSS](https://wiremock.org/) engine under the hood.
This architecture creates a clear separation of concerns:
- The **control plane** (management, UI, collaboration) remains in WireMock Cloud
- The **execution plane** (mock API execution) runs wherever you need it - locally via CLI, in your environments via **WireMock Runner** or in WireMock Cloud.
This is what makes hybrid deployment possible, and it's why **WireMock Runner** is sometimes referred to as "hybrid mode."
## Why WireMock Runner Exists
Traditional API mocking solutions force teams to choose between two extremes:
**Fully cloud-based** approaches offer convenience and collaboration but struggle when APIs live behind firewalls, when teams need fast local feedback loops, or when security policies prohibit external connections.
**Fully self-hosted** approaches provide control and privacy but require significant infrastructure investment, eliminate the benefits of cloud collaboration, and create maintenance overhead.
WireMock Runner was designed to resolve this tension. It enables teams to adopt the workflow that matches their needs rather than adapting their needs to match the tool's constraints.
## How WireMock Runner Works
The Runner operates as a containerized service with two primary modes:
### Record Mode
In record mode, the Runner automatically creates or updates mock APIs by capturing real API traffic. This allows teams to build or refresh mock specifications from actual service behavior, keeping mocks aligned with reality as APIs evolve.
Recording can happen locally during development, in CI/CD during integration tests or deployments, or in any environment where you need to capture API interactions (see [Recording on Kubernetes](/runner/recording-multiple-apis-on-kubernetes) for an example).
### Serve Mode
In serve mode, the Runner serves mock APIs locally, responding to incoming requests based on stub definitions — all without requests ever leaving your infrastructure.
Before the Runner can serve a mock API locally, the mock specification must first be pulled from WireMock Cloud to your local machine using the WireMock CLI:
`wiremock mock-apis pull
HTTP Basic is a widely supported part of the HTTP standard supporting username/password authentication.
An HTTP resource secured with HTTP Basic will result in a browser prompting the user
with a username/password dialogue box on their initial visit.
Alternatively, an API client can pre-emptively authenticate by sending a header of the form
`Authorization:Basic
WireMock Cloud can also authenticate requests based on a match expression against any header.
The match expression works in the same way as header matches in the stub creation form,
whereby you specify the header name, predicate and expected value.
### OpenID Connect authentication
For [Enterprise plan users](https://www.wiremock.io/get-pricing), WireMock Cloud can authenticate requests via an
OpenID Connect authorization server.
Requests must contain an HTTP header whose value is a [JWT](https://jwt.io) generated by the configured authorization
server.
The value of the Authorization header field must be the name of the HTTP header that will contain the JWT (usually
`Authorization`, but any valid HTTP header name is allowed).
The value of the Issuer URL field must be the base URL of the authorization server.
The authorization server is expected to be configured as per
[the OpenID Connect specification](https://openid.net/specs/openid-connect-discovery-1_0.html).
Specifically `/.well-known/openid-configuration` contains the required configuration information, including the URL to
the JSON Web Key Set (JWKS) that contains the key(s) to verify the JWTs' signatures.
The value of the Audiences field can optionally be a set of required audiences.
If this field's value is non-empty, every JWT's
[`aud` claim](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3) must contain all of these audiences for the
JWT to be considered valid.
### Audit Events Overview
Source: https://docs.wiremock.io/audit-events/overview
WireMock Cloud generates audit events when you perform various actions within your account. For example, creating or
deleting Mock APIs, changing settings or logging in and many more. For our enterprise customers we provide the ability
to push these audit events to an AWS S3 bucket stored within your AWS account.
## Usage
The audit event feature is only available to users on our Enterprise or Enterprise Trial plans and you will need to be
an organisation administrator to create and manage audit event destinations.
To create and manage your S3 bucket destination, navigate to the [Organisation Page](https://app.wiremock.cloud/account/organisation)
on your account. On this page you will see the `Audit Events` section.
This is where you will create and manage your S3 audit event destination. To set up an S3 audit event destination you
will need to configure your AWS account with an S3 bucket and a role to allow WireMock Cloud to push audit events to that
bucket.
## Configure Your AWS Account
The first step in setting up your S3 audit event destination is to configure your AWS account to allow WireMock Cloud
to save audit events to your bucket. You can do this in the following way:
* Create the S3 bucket `
* Click on the `Save` button to add the S3 audit destination to your organisation
Once you have saved the audit destination, you will see some documentation you can copy to make sure the role permission
and trust relationship you created above is correct. For a newly created audit destination you should see the status
message - `Status: Audit events are yet to be sent to this destination`
## Testing Your S3 Audit Event Destination
Now you saved the S3 audit event destination you can test it to make sure everything works end to end. Clicking on the
`Test` button will make WireMock Cloud attempt to post a test file to the bucket you created above. If all works
correctly the button will turn green and you should have a new file saved to your S3 bucket called `test-wiremock-cloud-integration.txt`.
This file will contain the date and time the test was performed.
Should an error occur trying to post the file to your S3 bucket, an error will be displayed to help you diagnose the issue.
## Deleting Your S3 Audit Event Destination
If you no longer require audit events to be sent to your S3 bucket you can delete the audit event destination from your
organisation. This will stop audit events being set to your S3 bucket. To do this you can click on the `Delete`
button. This will display a confirmation dialog to allow you to confirm the deletion.
Clicking on `No` will close the dialog and no action will be taken, clicking on `Yes` will delete your S3 audit event
destination and no more audit events will be sent.
## Sending Audit Events To Your S3 Bucket
WireMock Cloud will send audit events to your S3 bucket in batches every 10 minutes. There is a lookback window of
7 days for audit events. This means if you are setting up an S3 audit event destination and have been a customer for
a while, the first batch of audit events sent to your bucket will span back 7 days prior to the date you setup the
destination.
Once audit events are successfully being sent to your bucket you will see the status message update on the Organisation page:
If WireMock Cloud encounters an error while sending audit events to your S3 bucket, the status will be updated to
highlight the error. If audit events have been successfully sent in the past, the error will also contain the date the
last successful attempt was made:
Audit events are saved in your S3 bucket using the following structure:
```
|── 2025-02
| |── 01
| | |── 2025-02-01T13-45-12-789Z-wjg0yr69.json
| |── 02
| |── 2025-02-02T13-32-12-789Z-16oe0mgo.json
| |── 2025-02-02T14-29-12-789Z-9lrrjdm6.json
|── 2025-03
|── 02
| |── 2025-03-02T13-23-12-789Z-kr731z1.json
|── 03
|── 2025-03-03T13-45-12-789Z-9odlj3w3.json
|── 2025-03-03T14-29-12-789Z-38o4klr7.json
```
Each file follows the [new line delimited JSON specification](https://github.com/ndjson/ndjson-spec).
Audit events for the following items in WireMock Cloud are sent to your S3 bucket:
* Mock APIs
* Users
* Teams
* Organisations
* API Templates
* API Template Catalogues
* Data Sources
* Database Connections
* Keys
* Stub Mappings
* Mock API Settings
* Subscriptions
* Open API Git Integrations
* API Keys
* S3 Audit Destinations
More information about working with the audit event json can be found [here](./working-with-audit-events).
## Limits
You can read more about [plan limits here](./plan-limits/).
### Audit Event Destinations - Plan Limits
Source: https://docs.wiremock.io/audit-events/plan-limits
WireMock Cloud applies limits to audit event destinations dependent upon the plan your organisation is subscribed to.
On the enterprise or enterprise trial plans, an account is limited to 1 audit event destination. Accounts on the free
plan do not have access to this feature. If you are on the free plan and would like access to this feature,
[contact the WireMock team today](https://www.wiremock.io/contact-now) to discuss an enterprise plan for your organisation.
## Disabled Audit Event Destinations
If an account/organisation is downgraded to a plan that causes their audit event destinations to exceed the new plan's
limits, the exceeding destinations will be disabled. This means WireMock Cloud will no longer send audit events to
those destinations.
Disabled destinations can be enabled at any time by [upgrading to a different plan](https://www.wiremock.io/contact-now).
### Versioning
Source: https://docs.wiremock.io/versioning/overview
WireMock Cloud supports versioning of your mock APIs. This means that as you create and configure your mock APIs, a
version history is kept for each API. This allows you to easily revert to a previous version of your API, or to
compare the differences between two versions.
## Usage
### Accessing your mock API version history
The version history for your mock API is available on the mock API menu bar. Click on the `Version history` link to
access the version history.
This will take you to the version history page for your mock API where you will be able to see a list of the most recent
commits.
### Commits
A commit is a collection of changes to your mock API and is created when you create, modify or delete assets
associated to your mock API - stubs, settings, GraphQL schemas, gRPC definition files, OpenAPI schemas, etc.
Each commit will have a timestamp of when commit was made to the API. If the commit is made by an authenticated user
(as opposed to the system), the user's username will be displayed alongside the commit.
### Changes
Changes are the individual changes that were made to your mock API. To view the changes associated with a commit, click
on the `View changes` link to the right of the commit. This will display one or more changes highlighting what was
changed and how. For example, the following example shows a change for a stub creation in the Mock API:
### Viewing what actually changed
You can click on any of the changes in the list to view the actual changes that were made. Where possible, this will
show you the diff highlighting what was added or removed.
In the above example, the left side of the diff shows the stub before the change was made (it didn't exist so this is
empty), and the right side shows the stub after the change was made. (All the stub is marked as 'green' because it was
created in this change)
The diff view is available where we have a text representation of the change. For binary Mock API assets,
(like [gRPC](../grpc/overview) descriptor files) changes to those files are recorded but the diff view is not available.
### Restoring to a previous version
The buttons above the diff shows the restore actions you can take on either side of the diff.
In the example below, the right side of the diff has no action available because it shows the most recent
version of the stub. The left side of the diff has an action available to restore the change. Because this change
shows a stub creation, the 'restore' action is to delete this stub.
Clicking on the `Delete` button will display a confirmation dialog asking if you want to proceed with the deletion.
Clicking the `No` button will exit the confirmation dialog without deleting the stub. Clicking the `Yes` button
will 'restore' the change and delete the stub.
Once you have deleted a stub, the stub will no longer be available in your mock API and a new commit will be created
with the stub deletion. The diff will show the stub as being deleted:
You will see the button has now changed to `Restore` to allow you to restore the stub. Clicking on the `Restore`
button will display a confirmation dialog asking if you want to proceed with the restore.
As before, clicking the `No` button will exit the dialog without restoring the stub. Clicking `Yes` will restore the
stub and create a new commit with the stub creation.
The same applies to modifying - a new commit will be created with the change. The diff will show the change from the
previous version to the new version:
You will notice in the image above that no `Restore` button is available on the right hand side of the diff. This is
because the right hand side of the diff shows the most recent version of the stub. The left hand side of the diff has an
`Restore` button available to restore the change. If the commit you were looking was not the most recent version of the
stub, you will see a `Restore` button on both sides of the diff allowing either side of the diff to be restored:
Versioning is available for mock API stubs, settings, chaos, GraphQL schemas, gRPC definition files and OpenAPI schemas. Updating
any of these assets will create a new commit. Some commits are created automatically for you.
For example, if you are working on a [REST mock API](../openAPI/openapi) and you have automatic generation of OpenAPI to
stubs enabled. Updating a stub will create a new commit for the change to the OpenAPI and a new commit for the change to
the stub.
### Importing
Importing into your mock API can generate multiple changes in the one commit. For example, if you imported a file that
created multiple stubs, each of those stub creation changes will be recorded in a single commit.
## Restoring a Mock API to a previous commit
When you click on the `View changes` link for a commit, you will see the changes between the commit you have selected
and the previous commit. This is great for when you want to cherry-pick specific changes and restore individual items
in your mock API.
However, if you want to restore the entire mock API to a previous version, you can do so by clicking on the `Compare with latest`
link next to a commit
This will show you all the changes between the current version of the mock API (the latest commit) and the commit you
have selected. You can then click on the `Restore all changes` button next to the commit you want to restore to.
As with and restores, this will create a new commit with all the mock api changes from the selected commit. This will
include any changes to the mock API settings, stubs, chaos, GraphQL schemas, gRPC definition files and OpenAPI schemas.
When you click on the `Restore all changes` button, you will be prompted to confirm that you want to restore the entire
mock API to the selected commit.
Clicking `Yes` will restore the entire mock API to the selected commit and clicking `No` will exit the confirmation dialog
without making any changes.
## Limits
You can read more about [plan limits here](./plan-limits/).
If you have feedback or questions on our Versioning functionality as it evolves, we'd love to hear from you.
Please [get in touch](mailto:support@wiremock.io).
### Versioning - Plan Limits
Source: https://docs.wiremock.io/versioning/plan-limits
WireMock Cloud applies limits to versioning dependent upon the plan your organisation is subscribed to.
On the enterprise or enterprise trial plans, mock API versions will be kept for a period of 18 months. There is no limit
to the number of changes that can be created in this time. Accounts on the free plan are limited to 5 changes and
those changes will be kept for a period of 1 year.
If you are on the free plan and would like addition versioning capacity, [contact the WireMock team today](https://www.wiremock.io/contact-now)
to discuss an enterprise plan for your organisation.
## Downgrading to a lower plan
If an account/organisation is downgraded to a plan that causes their version changes to exceed the new plan's
limits, the exceeding changes will be deleted down to the limits of their new plan.
### Dynamic State Shopping Basket Example
Source: https://docs.wiremock.io/dynamic-state/basket-example
To learn how to use WireMock Cloud's Dynamic State capabilities, let's look at a working example of using dynamic state
to mock CRUD operations on a shopping basket.
## Getting started
You can start your own copy of this example Mock API from a template just by clicking on this link:
[Launch Shopping Basket Mock](https://app.wiremock.cloud/new-mock/stateful-shopping)
## Exploring the behaviour
### Get an empty basket
Let's start by seeing what is in a shopping basket. Make a request to any basket:
3. Supply a **POST endpoint page** (e.g., `/users`):
4. Provide a **sample request body** for the `POST`
e.g.:
```json
{
"firstName": "Betty",
"lastName": "Boop",
"organization": "Finance"
}
```
5. Input a **correlated sample response body** for the given request body
e.g.:
```json
{
"contactId": "4",
"firstName": "Betty",
"lastName": "Boop",
"organization": "Finance",
"created_utc": "2025-02-28T15:58:35Z"
}
```
6. At the bottom of the dialog, select which operations you'd like stubs to be created for:
7. Click the **Create Stateful set** button:
New stubs will be created that are automatically configured with stateful functionality.
- A **POST** stub that creates a new resource in the mock API's stateful memory
- A **GET** stub that lists all of the resources stored in the mock API's stateful memory
- A **GET** stub that retrieves a stored resource by its identifier
- A **PUT** stub that updates the stored data of a resource
- A **DELETE** stub that removes the stored resource
- A **DELETE** stub that removes all stored resources from the mock API's stateful memory
- A fallback **404 response** for unknown requests
You will want to further modify the stubs to better simulate the API's real-world stateful behavior.
### Teams and Collaboration
Source: https://docs.wiremock.io/security/teams-and-collaboration
The basic unit of ownership in WireMock Cloud is the Organisation. Mock APIs,
users and teams all belong to a single organisation. View your organisation by
clicking on the [Organisation page](https://app.wiremock.cloud/account/organisation) under your account.
Here you will see all the teams and users in your organisation:
There are two roles for users in an organisation: **Member** and **Admin**.
A **Member** can create and interact with mock APIs, API templates and teams.
In addition an **Admin** can:
* invite other users to the organisation
* remove users from the organisation (provided at least one Admin remains)
* change the role of any member of the organisation (provided at least one Admin
remains)
* administer all mock APIs, teams and other resources belonging to the
organisation
### Inviting users
An admin can enter the email address of a person not yet in the organisation,
and a role, to invite that person to join the organisation. They will then show
up in the "Pending Invites" section.
Organisation members and pending invitations count towards your subscription plan's total number
of seats. You can see your usage and limits on the [Usage page](https://app.wiremock.cloud/account/usage) under your account.
## Teams
Any member of an organisation can create a team (provided the organisation is on
a plan which allows multiple members).
The person who creates the Team will automatically be given the Admin
role on that team. In addition all organisation admins can administer a team.
There are two roles for users in a team: **Member** and **Admin**.
A **Member** will inherit whatever permissions the team has been granted.
In addition an **Admin** can:
* add other members of the organisation to the team
* remove users from the team
* change the role of any member of the team
An organisation admin can enter the email address of a person not yet in the
organisation, and a role, to simultaneously invite that person to join the
organisation _and_ add them to the team.
## Mock APIs
Any member of an organisation can create a mock API.
The person who creates the mock API will automatically be given the Admin
role on that mock API. In addition all organisation admins can administer a mock
API.
Mock APIs can be shared with other members of your organisation by clicking the
"Share" button on the API:
Mock APIs can be shared with "All in organisation", any of the Teams
belonging to the same organisation as the mock API, and any individual members of the organisation.
When sharing a mock API, you can choose the role of the organisation, team or
person you are sharing the API with as one of **Admin**, **Write** or **Read**.
* **Read** allows: viewing the API, its stubs, and who else has permissions on it.
* **Write** also allows changing the settings of the API, and adding, changing or
deleting the stubs on the API.
* **Admin** also allows deleting the mock API, and adding & removing people, teams & the organisation, or
changing their roles, in the "Share" widget.
An organisation admin can enter the email address of a person not yet in the
organisation, and a role, to simultaneously invite that person to join the
organisation _and_ give them that role on the mock API.
## Single Sign-on (SSO)
WireMock Cloud supports auto-provisioning and SSO for user management via any SAML 2.x capable IdP.
### The SAML Identity Provider Mock
Source: https://docs.wiremock.io/security/saml-idp-mock

These instructions will help you set up a SAML Identity Provider Mock in your WireMock Cloud account.
The SAML IDP Mock is a template that simulates a SAML Identity Provider (IdP). It
generates signed SAML responses with configurable user attributes, making it suitable
for testing SAML-based SSO integrations without needing a real IdP.
Instructions are provided for using it as an Auth0 Enterprise Connection, but should be
broadly applicable to use with any other Service Provider (SP).
## Setting up the mock
To set up the SAML Identity Provider Mock in your WireMock Cloud account, follow these steps:
1. Log in to you [WireMock Cloud](https://app.wiremock.cloud/mock-apis) account.
2. Click **Create new mock API**.
3. On the `Choose protocol` screen, choose `Template library`.

4. On the template library screen, search for `SAML` and click **Create Mock API** on the `SAML IDP` template.

5. Give your mock API a name and click **Continue**.
6. This will create the mock API from the template in your WireMock Cloud account.
## How it works
The template provides an interactive web UI with a three-step flow:
1. **Instructions** (`/`) — Setup guide for connecting the mock IdP to your Service Provider (e.g. Auth0)
2. **Login** (`/login`) — A form to configure the post-back URL, email address, and optional extra SAML attributes
3. **Send Response** (`/send-response`) — Builds a signed SAML response and POSTs it back to your SP's ACS URL
The mock IdP also serves its X.509 signing certificate at `/certificate.pem`.
## SAML response structure
The response includes:
- **Issuer** — mock API's base URL
- **Subject** — NameID using email (format: `emailAddress`)
- **Conditions** — NotBefore (now - 1 min), NotOnOrAfter (now + 5 min), with audience from the SAML request
- **Attributes** — `email` attribute plus any extra `
From this page you can create new keys, page between existing keys, and delete keys, as well as search for specific
keys by name.
### Creating new keys
Clicking the `Create new key` button on the main keys page will take you to a new page containing a form to enter the
desired name of the new key.
Saving this new key will generate a secure key pair, and the public key for this key pair will be displayed.
This key can then be [attached to other parts of WireMock Cloud](#usage).
The private key is stored in encrypted form and only decrypted briefly when in use via a secure decryption service.
### Moderating existing keys
To view and update a key, click on its name from the main key page.
From here, a key's name can be updated, and the key can be shared with others in your organisation.
### Working with Audit Event JSON
Source: https://docs.wiremock.io/audit-events/working-with-audit-events
Each file saved in your S3 bucket follows the [new line delimited JSON specification](https://github.com/ndjson/ndjson-spec).
Each line of json in the file conforms to the following json schema:
```json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"timestamp": {
"type": "string",
"format": "date-time"
},
"eventId": {
"type": "string",
"format": "uuid"
},
"entity": { "$ref": "#/definitions/entity" },
"parentEntity": { "$ref": "#/definitions/entity" },
"organisation": { "$ref": "#/definitions/entity" },
"principal": { "$ref": "#/definitions/entity" },
"clientType": {
"anyOf": [
{
"type": "string",
"enum": [
"UI",
"API",
"SYSTEM",
"ADMIN",
"CLI"
]
},
{ "type": "string" }
]
},
"action": {
"anyOf": [
{
"type": "string",
"enum": [
"CREATE",
"UPDATE",
"DELETE",
"SIGNUP",
"LOGIN",
"ACL_GRANT",
"ACL_REVOKE",
"INVITE"
]
},
{ "type": "string" }
]
},
"before": {
"type": "object"
},
"after": {
"type": "object"
},
"subject": { "$ref": "#/definitions/entity" },
"permission": {
"oneOf": [
{
"type": "string",
"const": "ALL_PERMISSIONS"
},
{
"type": "object",
"properties": {
"permissions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"friendlyId": {
"type": "string"
}
},
"required": [
"id",
"friendlyId"
]
}
}
},
"required": ["permissions"]
}
]
}
},
"required": [
"timestamp",
"eventId",
"entity",
"organisation",
"principal",
"clientType",
"action"
],
"definitions": {
"entity": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"entityType": {
"anyOf": [
{
"type": "string",
"enum": [
"MOCK_API",
"USER",
"TEAM",
"ORGANISATION",
"API_TEMPLATE",
"API_TEMPLATE_CATALOGUE",
"DATA_SOURCE",
"KEY",
"DATABASE_CONNECTION",
"STUB_MAPPING",
"MOCK_API_SETTINGS",
"SUBSCRIPTION",
"OPENAPI_GIT_INTEGRATION",
"API_KEY",
"S3_AUDIT_SINK"
]
},
{ "type": "string" }
]
}
},
"required": ["id", "name", "entityType"]
}
}
}
```
## AI & agents
### WireMock Cloud AI
Source: https://docs.wiremock.io/ai-mcp/ai-101
WireMock Cloud provides API simulation capabilities that integrate with AI development tools through the Model Context Protocol (MCP). This enables AI assistants to create, manage, and test against mock APIs directly within your development environment.
## Key Capabilities
**API Simulation**
Create mock APIs from existing code, OpenAPI specifications, or natural language descriptions using AI assistance.
**Codebase Integration**
Generate mocks that reflect your existing API patterns and data structures by analyzing your codebase.
**Testing with AI Agents**
Allow AI coding assistants to validate generated code by testing against realistic mock responses.
**Independent Development**
Work on features that depend on APIs still in development by creating temporary mock implementations.
## Installation
The recommended way to get started is the [WireMock Cloud agent skills plugin](/ai-mcp/agent-skills) - it gives your coding agent both expert WireMock Cloud workflows and a ready-configured connection to the hosted MCP server, with no separate setup step.
[**View the plugin installation guide →**](/ai-mcp/installation)
If you'd rather connect an AI tool directly to the MCP server without the skills plugin, see the [MCP server installation guide](/ai-mcp/mcp-installation), which covers both the remote, hosted server and a local, CLI-based alternative.
## Supported Tools
WireMock integrates with AI development environments via the Model Context Protocol:
VS Code
Copilot
Transform static mock APIs into dynamic, stateful versions that maintain state between requests. AI assists in validating mock behavior as it evolves, enabling realistic simulation of complex API interactions and multi-step workflows.
Use AI to explore and document undocumented APIs by automatically discovering endpoints, analyzing responses, and generating comprehensive documentation. This is especially valuable when working with legacy systems or third-party APIs.
Detect and resolve discrepancies between mock APIs and their OpenAPI specifications using AI assistance. Automatically identify when mocks drift from intended behavior and update them to maintain consistency with API contracts.
Prototype a GraphQL API schema, instantly simulate it then refine its data and improve realism.
Generate mock endpoints for your application's API dependencies and swap real APIs for mocks during development and testing. This enables isolated development without external service dependencies, improving reliability and reducing development costs.
Leverage AI agents to prototype APIs that don't yet exist, allowing teams to develop against future services before backend implementation. Create realistic endpoint behaviors and response patterns to unblock frontend development and testing workflows.
Configure automatic authentication for AI-driven HTTP requests without exposing credentials to the language model. Set up domain-based authentication with OAuth, API keys, or custom headers to enable secure API exploration and testing workflows.
Or, follow these instructions:
- Open Settings->Cursor settings.
- Navigate to Tools & Integrations.
- Click New MCP Server. This opens `mcp.json`.
- Add the WireMock server:
```json
{
"mcpServers": {
"WireMock": {
"url": "https://mcp.wiremock.cloud/mcp"
}
}
}
```
- Save the file. Cursor will show a "needs authentication" indicator next to the server - click **Connect** to complete an OAuth sign-in in your browser.
### Step 2: Confirm your setup
To confirm everything is working correctly, check that you're logged in to WireMock Cloud by running the following prompt:
```
Am I logged into WireMock Cloud?
```
If logged in, you'll see your account details rather than being prompted to sign in.
### Step 2: Confirm your setup
To confirm everything is working correctly, check that you're logged in to WireMock Cloud by running the following prompt in Cascade:
```
Am I logged into WireMock Cloud?
```
If logged in, you'll see your account details rather than being prompted to sign in.
Or, follow these instructions:
- Open Settings->Cursor settings.
- Navigate to MCP.
- Click Add new MCP server.
- In the dialog, configure your server to run this command:
```bash
wiremock mcp
```
- Verify Installation by looking for the green status dot next to the MCP server and the list of tool names.
If you have an existing real API integration, you can replace it with a WireMock stub. Generate the mock from documentation, source code, or other external description formats. This enables you to test your app in isolation without depending on live services.
### Step 4: Confirm your setup
To confirm everything is working correctly, check that you’re logged in to WireMock Cloud by running the following prompt:
```
Am I logged into WireMock Cloud?
```
If logged in, you’ll see your account details rather than being prompted to sign in.
- You should see "wiremock" in the list of configured MCP servers.
### Step 4: Confirm your setup
To confirm everything is working correctly, check that you're logged in to WireMock Cloud by running the following prompt in Claude Code:
```
Am I logged into WireMock Cloud?
```
If logged in, you'll see your account details:
### Step 4: Confirm your setup
To confirm everything is working correctly, check that you're logged in to WireMock Cloud by running the following prompt in Cascade:
```
Am I logged into WireMock Cloud?
```
If logged in, you'll see your account details rather than being prompted to sign in.
To start the login process, click on the **Log in** link. This performs two things:
- shows a balloon popup with your verification code
- opens the login page in your web browser showing you a verification code
In case the page would not open, you can copy the verification URL from the popup.
Make sure that the two codes match, then confirm the device code. In a few seconds the IDE will show you another balloon
confirming your login.
### From the plugin settings
You can also log in to your account via the plugin settings at **Settings | Tools | WireMock**.
The flow is similar to the one described in the previous section, but it is handled entirely on the settings UI,
and you also have the option to **Cancel Login**.
When the login is successful, the UI will show you the email address you are logged in with,
or will notify you if a problem occurred during the login.
#### Use with On-Premise Edition
The plugin also supports work with the on-premise edition of WireMock Cloud. To turn on this feature, enable
the **Use with On-Premise Edition** option, update the necessary configuration values, and log in.
If you are already logged into a different installment of WireMock Cloud, make sure to log out, save the settings,
and log in again.
## Create mock APIs and import stubs
If you want to convert local stub mappings to remotely hosted WireMock Cloud mock APIs, you can do so: open a stub mapping file,
then click on the **Create mock API** link in the top notification,
or the
The following API types are supported:
- Unstructured (WireMock)
- REST
- [GraphQL](/graphql/overview) (+ non-federated schema)
- [gRPC](/grpc/overview) (+ descriptor file)
If you choose GraphQL or gRPC you must also upload a schema/descriptor file with them. Creating a mock API without them is not permitted.
### Completion of the API creation
The creation of the mock API and data upload into it is performed in two or three separate phases depending on the API type:
- API creation and stub upload for Unstructured and REST,
- API creation, stub upload and schema/descriptor upload for GraphQL and gRPC
Thus, when all phases finish without any issue, a separate balloon notification appears for each phase.
The first one also provides a link with which you can easily open the new API in your browser.
If any phase fails for any reason, notifications with appropriate messages will let you know of the failure and the reason of it.
## Import stubs into existing mock APIs
Besides uploading stubs into newly created APIs, you can also upload them into APIs that already exist in your WireMock Cloud account.
You can do so by opening a stub mapping file, then clicking on the
### Search
When opening the dialog, it displays all available mock APIs. After that you can perform searches with arbitrary query strings (it is case-insensitive)
either by clicking the
### Pagination
This component lets you navigate through the current result set. It supports moving to the **First**, **Previous**, **Next** and **Last** pages when applicable,
as well as to arbitrary pages.
To initiate the navigation to a specific page, specify a valid page number and hit Enter. If it is initiated with a number
- less than 1, or a non-integer, it will load the first page
- greater than the total number of pages, it will load the last page
In addition, when an invalid page number is entered, the field displays an appropriate message, for example:
### Initiating the stub import
When the dialog is OKed, the stub import begins, and the same logic, including handling failure scenarios,
is performed as when uploading stubs via the [Create mock APIs and import stubs](#create-mock-apis-and-import-stubs) feature.
### Support for WireMock OSS
Source: https://docs.wiremock.io/ide-integrations/jetbrains/oss-features
## Create WireMock stubs
### Create basic WireMock stub from scratch
If a JSON file is placed in the **mappings** or **messages** folder, or contains the `"mappings"` or `"messageMappings"`key,
the plugin recognizes it as a WireMock stub file and provides appropriate coding assistance.
1. In the **Project** tool window, right-click a folder (or press ⌘СmdN or AltInsert) and select **New | File**.
2. In the **New File** dialog that opens, enter a name of the file. For example, you can enter `mappings/my-stub.json`, and the plugin will create the **mappings** folder and place the new file within it.
3. Start typing a key to get suggestions for applicable keys and their quick documentation.
#### Additional coding assistance
This coding assistance also includes the following features (supporting both HTTP and message stubs):
- Code completion of HTTP methods in JSON properties like `request.method` in HTTP stubs, and `trigger.requestPattern.method` and other request pattern locations in message stubs
- Code completion of HTTP headers in JSON properties like `request.headers.*`
- Server URL references in JSON properties like `request.url`, and in parameters of Java methods like `WireMock.urlEqualTo()`
The new stub file is saved as a [scratch](https://www.jetbrains.com/help/idea/scratches.html) under **Scratches and Consoles | WireMock Stubs**.
### Create WireMock stubs from OpenAPI specification
1. Open an OpenAPI specification file.
2. Click
The new stub file is saved as a [scratch](https://www.jetbrains.com/help/idea/scratches.html) under **Scratches and Consoles | WireMock Stubs**.
## Run WireMock server
1. Open your stub file.
2. Click
This will start the WireMock server, and you can see it running in the **Services** tool window (**View | Tool Windows | Services** or press ⌘Сmd8 or Alt8).
To customize how IntelliJ IDEA starts the WireMock server, you can [modify the WireMock run configuration](#wiremock-run-configuration) or create a new one.
## Send HTTP requests
Use the IntelliJ IDEA [HTTP Client](https://www.jetbrains.com/help/idea/http-client-in-product-code-editor.html) to send HTTP request to the WireMock server and preview responses.
1. [Run your WireMock server.](#run-wiremock-server)
2. Open your stub JSON file.
3. Place the caret at your endpoint URL, press ⌥Option↩Enter or Alt↩Enter (**Show Context Actions**), and select **Generate request in HTTP Client**.
You can view the stub response in the **Services** tool window.
## Enable support for Handlebars templates
IntelliJ IDEA provides coding assistance for templating language used in WireMock response templates. To use this feature, you need the [Handlebars/Mustache](https://plugins.jetbrains.com/plugin/6884-handlebars-mustache) plugin to be installed and enabled.
1. Open your HTTP or message stub JSON file.
2. In the upper-right part of the editor, click
- Completion for [request model](https://wiremock.org/docs/response-templating/#the-request-model) and [message model](https://wiremock.org/docs/messaging/stubbing/#available-template-variables) attributes
### Main parameters
- **Name**: Specify a name for the run configuration.
- **Stubs file**: Location of the JSON file with WireMock stubs to run.
- **Server port**: HTTP port number for the WireMock server. Enter `0` to dynamically determine a port.
### Modify options
- **Verbose output**: Turn on verbose logging to stdout (equivalent for the `--verbose` option).
- **Enable global Handlebars templating**: Render all response definitions using Handlebars templates by passing the `--global-response-templating` [WireMock command line option](https://wiremock.org/docs/standalone/java-jar/#command-line-options).
- **JRE**: Select a JRE if you wish to run WireMock in a different runtime environment than JBR.
### Logs
Specify which log files generated while running the application should be displayed in the console on the dedicated tabs of the [Run](https://www.jetbrains.com/help/idea/2025.3/run-tool-window.html) tool window.
### Before launch
Select tasks to be performed before starting the selected run/debug configuration.
### Integration with Claude Code
Source: https://docs.wiremock.io/ide-integrations/jetbrains/claude-code-integration
## What is Claude Code?
The [Claude Code](https://plugins.jetbrains.com/plugin/27310-claude-code-beta-) plugin is Anthropic's integration of Claude Code
into the JetBrains ecosystem. Explore its [documentation](https://code.claude.com/docs/en/jetbrains) for details.
## WireMock MCP server
WireMock, via its CLI tool, provides its own [MCP server](/ai-mcp/mcp-installation) implementation with which you can
manage and work with your WireMock Cloud resources from any MCP-compatible AI tool.
In order to be able to use the WireMock MCP server in Claude Code, the server configuration must be added to one of its configuration files.
The IDE plugin helps simplify that process, and also makes it possible to use the MCP server with the WireMock Cloud account you are logged in with
inside the IDE.
It provides two ways of managing the MCP server configuration:
- on-demand, one-click addition, update and removal via the plugin settings
- automatic update at certain points of the user workflow
This integration supports Claude's **user**, **project** and **local** scopes.
### On-demand configuration
On-demand actions are available at two distinct locations:
- via a balloon notification after each project launch
- via the plugin settings at **Settings | Tools | WireMock**
#### Balloon notification
First of all, this notification is tied to the presence of the Claude Code IDE plugin. It is displayed only when
the Claude plugin is installed.
If that condition is satisfied, the notification appears after each project launch (that is to support the *local* and *project* scopes),
but only once per project to minimize distraction.
The balloon provides the following set of actions:
- Add server to user scope
- Add server to project scope
- Add server to local scope
- Don't show again
The addition actions open a new tab in the **Terminal** tool window
(based on the shell configured in **Settings | Tools | Terminal | Application Settings | Shell path**),
and execute the `claude mcp add ...` CLI command with the proper configuration for the MCP server.
By choosing **Don't show again**, the balloon will no longer be displayed for any projects in the future.
#### Plugin settings
MCP related options are available in the **MCP Server Configuration** section of the WireMock plugin settings.
After choosing the Claude Code scope you want to manage the MCP server of, you can use the following options:
- **Add WireMock MCP Server** (
### Automatic updates
In a few scenarios the WireMock MCP server configuration and credentials are updated automatically in all supported Claude Code config files,
and the input configuration file.
This is to make sure that the configuration stays up-to-date with the current plugin settings, login status, and the currently used IDE.
The update happens in the background, and it is due to how the server configuration is built.
See the [MCP server structure](#mcp-server-structure) section below for details.
These scenarios are:
- you log in to your WireMock Cloud account in the IDE
- you log out from your account
- you save the WireMock plugin settings
- the IDE is launched
Once you've saved the stub, point your browser to [http://localhost:9000](http://localhost:9000).
You should see the to-do items in your response body listed in the page:
What has happened here is that the Spring Boot app has made a REST request to WireMock Cloud, which was matched by the stub you just created.
The stub returned a JSON response which the app parsed and rendered into an HTML page.
Now try modifying one or more of the item descriptions in the stub response and saving it, then refreshing the page. You should
immediately see your new items in the to-to list.
## Step 2 - simulating the posting of a new item
Next we're going to simulate a new item being added to the list via a POST request.
For this you'll need another new stub, this time for `POST` to `/todo-items` , response `Content-Type` header `application/json` and the following JSON in the response body:
```json
{ "message": "Successfully sent new item." }
```
Your stub should look like this:
Once that's saved, go to the to-do list page and add a new item by typing a description in the field and clicking the button:
You should now see the success message you put in the stub response:
You'll notice that the contents of the list hasn't changed. This is because WireMock Cloud stubs aren't stateful - the app will load whatever is in the `GET /todo-items` stub you created at the start until you change it. However, if you visit the request log in the WireMock Cloud UI you can confirm that the request you expected actually arrived:
## Step 3 - posting a new item fails
In this step we're going to deliberately return an error from the API in order to test that the app behaves appropriately.
Navigate to the `POST /todo-items` stub you created in the previous step and clone it (using the Clone button at the end of the form).
In the newly cloned stub, expand the Advanced section and give the stub a higher priority - 4 or less will work as the default is 5.
The reason we need to do this is to ensure that this and not the OK posting stub we cloned from is guaranteed to match an incoming `POST /todo-items`.
In the response section change the response code to 502 and the message in the JSON body to something suitable:
Now try adding a new to-do item as you did in Step 2. When after submitting it, you should see an error page like this:
### Automated Testing with Java
Source: https://docs.wiremock.io/samples/automated-testing-with-java
Everything that can be done with WireMock Cloud's web UI can also be done via its APIs. This can be useful when automating
testing, as it allows stubs to be configured and torn down on-demans by individual test cases rather than it being
necessary to configure an entire test suite's stubs manually up-front. Working this way can make your tests a lot more
readable as it makes their preconditions explicit.
WireMock Cloud's API is 100% compatible with [WireMock's](http://wiremock.org/docs/api/). This means that WireMock
can be used as a Java client for WireMock Cloud.
## Adding WireMock to your project
WireMock is distributed in two different types of JAR - a standard "thin" JAR, and a "fat" standalone JAR. The latter of these
contains all of WireMock's dependencies and repackages (shades) most of these. Either can be used as a dependency in your
project and which you choose depends primarily on whether you have dependencies already present that conflict with WireMock's.
Picking the standalone version generally avoids these problems but at the cost of a larger JAR download.
If you're using Gradle you can add WireMock to your build file's dependencies as follows. Choose one of:
```
testImplementation 'org.wiremock:wiremock:3.12.1' // thin JAR
testImplementation 'org.wiremock:wiremock-standalone:3.12.1' // standalone JAR
```
Or if you're using Maven, choose one of:
```xml
You can check that your new API is live by copying the base URL by clicking the icon
to the right of the box and making a request from your HTTP client (e.g. Postman):
## Basic contact list
A contact manager application is likely to have the ability to list all stored contacts.
Let's assume our imaginary API responds to `GET /v1/contacts` with JSON like:
```json
{
"contacts": [
{
"id": "11111",
"firstName": "Tom",
"lastName": "Smith",
"email": "tom.smith@example.com",
"dateAdded": "2021-01-03",
"companyId": "123"
},
{
"id": "22222",
"firstName": "Suki",
"lastName": "Patel",
"email": "spatel@example.com",
"dateAdded": "2020-11-12",
"companyId": "123"
},
{
"id": "33333",
"firstName": "Lexine",
"lastName": "Barnfield",
"email": "barnfield8@example.com",
"dateAdded": "2021-01-03",
"companyId": "234"
}
]
}
```
We can simulate this by creating a basic stub, matched on a `GET` with the exact
URL path `/v1/contacts`. Go to the Stubs page under your new mock API and hit the
new stub button:
.
Then in the request section, set the method to `GET`, the URL to `/v1/contacts`
and the URL match type to `Path`:
In the response section put the JSON in the body field, and for good measure
we'll also send a `Content-Type: application/json` header:
After hitting Save, you can now test the stub using WireMock Cloud's Test Requester or
your preferred HTTP client:
## Filtering via query parameters
REST APIs often allow collection resources like the contact list to be filtered
using parameters in the request's query string.
For instance, so that we can find contacts for a specific company our contact
manager might support filtering by company ID. For instance `/v1/contacts?companyId=123`
would return:
```json
{
"contacts": [
{
"id": "11111",
"firstName": "Tom",
"lastName": "Smith",
"email": "tom.smith@example.com",
"dateAdded": "2021-01-03",
"companyId": "123"
},
{
"id": "22222",
"firstName": "Suki",
"lastName": "Patel",
"email": "spatel@example.com",
"dateAdded": "2020-11-12",
"companyId": "123"
}
]
}
```
We'll simulate this by creating a similar stub to the first one, but with a
query parameter match and the filtered JSON document in the response body. To save some time we can
clone the first stub rather than starting from scratch, which can be done by
clicking Clone Stub at the bottom of the stub form.
Then we add a query parameter match for `companyId` equalling `123`:
And finally paste the filtered JSON in the body field:
You can find more detail on [matching different parts of incoming requests here](/advanced-stubbing/#advanced-request-parameter-matching).
[See here for the full list of available request matchers](/request-matching/matcher-types/) (such as `equalTo` and `contains`).
## Getting an individual contact
It's also very common for REST APIs to support retrieval of individual items of
data specified by an identifier in the URL path, so in our case we might fetch an
individual contact via a `GET` to `/v1/contacts/22222`.
We can stub a single data item in a very similar manner to the contact list we
created first, relying on exact URL path equality to match the request:
## Using URL regex matching and response templating to simulate many data records
If you only need to be able to return a small number of individual contacts then the above
approach of creating a stub per contact will work OK.
However, you may need return many
unique contact records e.g. because you're performance testing and want to spread
the load across realistic data volumes. In this instance you can use URL regex
matching and response templating to simulate the presence of many data items.
Let's modify the single contact stub we've already created. First we'll switch to
a looser URL match using the `Path regex` URL match type with the regular expression `/v1/contacts/[0-9]{1,10}` as the value.
This will match any URL path starting with `/v1/contacts` and ending with any
numeric ID between 1 and 10 characters long:
Then we'll enable templating in the response by ticking "Enable templating" and
make the response body more dynamic by replacing some elements with template helpers, giving us:
```json
{
"contact": {
"id": "{{{request.pathSegments.2}}}",
"firstName": "{{{randomValue length=6 type='ALPHANUMERIC'}}}",
"lastName": "{{{randomValue length=10 type='ALPHANUMERIC'}}}",
"email": "{{{randomValue length=12 type='ALPHANUMERIC'}}}@example.com",
"dateAdded": "{{{now offset='-3 months' format='yyyy-MM-dd'}}}",
"companyId": "123"
}
}
```
Now we can make a test request with any valid ID value (numeric, 1-10 characters)
and will receive a response with the ID field matching the value in the request URL
and some of the data randomised:
Unpacking what we've done here:
* `id` is now set from the 3rd segment of the incoming request URL's path, so it will always be the same as the requested contact ID.
* `firstName`, `lastName` and `email` are now random alphanumeric text (with a fixed domain name in the case of `email`).
* `dateAdded` is set to 3 months before today's date.
You can [learn more about response templating here](../response-templating/basics/) and [more about URL matching here](../request-matching/url/).
## Creating a new contact
At some point our contact manager API will need to be able to accept new contacts
in addition to just returning them. Commonly, REST APIs support sending a `POST`
request to the URL for a collection resource as a means to add new data items.
So our contact manager might accept `POST /v1/contacts`, returning a
response with status code `201 Created` and an empty body:
### More specific matching
In its current state, this stub will be matched regardless of the contents
of the request body, so a body with incorrectly structured JSON, XML or even no body
at all will still yield the `201` response.
If we want to ensure the stub is only matched when correctly structured JSON is
sent in the request but without requiring a set of exact values, we can add a body
matcher by clicking New body matcher and using JSONUnit as wildcards:
```json
{
"contact": {
"id": "${json-unit.any-string}",
"firstName": "${json-unit.any-string}",
"lastName": "${json-unit.any-string}",
"email": "${json-unit.regex}[a-z0-9+_.-]+@[^.]+\\.[^.]+$",
"dateAdded": "${json-unit.regex}[0-9]{4}-[0-9]{2}-[0-9]{2}",
"companyId": "${json-unit.any-string}"
}
}
```
Now if we make a request containing an incorrect JSON field (`name` instead of
`firstName` and `lastName`), we'll get a `404 Not Found` response
containing a diff report showing which part of the request didn't match:
## Simulating state changes
When posting a new item of data to a real API we'd expect it to be
stored and therefore returned on a subsequent `GET` request for
the collection or the individual resource. However, mock APIs by default don't
store any state, so making a request to add a new contact will have no effect on
the data returned later.
For most testing scenarios this isn't an issue, but in cases where more realistic
behaviour is required WireMock Cloud supports the concept of "stateful scenarios" whereby
the state of a scenario can be used to determine which stub to match.
If we wanted to, for instance, create a test case in which posting a new company
results in it appearing in the companies collection we can achieve this by creating three
stubs, all associated with the same scenario.
Firstly, we'd stub the initial response for `GET /v1/companies` (in much the same manner as we did
for contacts), returning a single company in the collection:
```json
{
"companies": [
{
"id": 123,
"name": "Boring Corp"
}
]
}
```
This time we'd put the stub in a scenario called "Companies" (the name is not important)
and require that the scenario be in the "Started" state in order for the stub to match:
Next, we'd create a second `GET` stub cloned from the first but with a second
company added to the collection:
```json
{
"companies": [
{
"id": 123,
"name": "Boring Corp"
},
{
"id": 234,
"name": "Az Tech"
}
]
}
```
This stub would also be in the "Companies" scenario but this time with a different
required state:
Finally, we'd configure the stub that handles the `POST` to advance the state of the scenario
so that it appears to have the effect of storing the new company:
### Testing the scenario
The first time we make a request to `GET` our companies we should see a single item in the collection:
Then we `POST` a new company:
Then when we fetch the companies list a second time we should see two companies
returned:
The scenario will now remain in state "2 companies" until it is manually reset,
which you can do by clicking Reset All Scenarios, which resets all scenarios to "Started".
You can [find out more about Scenarios here](../dynamic-state/stateful-scenarios/).
## Returning errors for specific requests
Sometimes we want to be able to support negative tests, for instance when the
API we're calling returns an error rather than the expected response. We can configure our mock API to return errors in response to specific requests
with the help of the priority stub parameter.
Let's suppose we want to test the case where our app tries to post a new contact
but the API returns a `503 Service Unavailable` response instead of the expected `201`.
If we configure a stub that expects specific data in the request body and give it
a higher priority than the existing `POST` stub that returns `201` then we can
send a request with appropriate data and see the error returned.
Start by cloning the existing `POST` stub for new contacts. Change the Priority value to a number
lower than `5` (`1` is highest).
Then we'll modify the body matcher so that it'll only
match when a specific piece of data is sent. One option here would be to substitute
the placeholders in the `equalToJson` body match we already have and this would
work fine if we were confident our test could produce exactly the same values each time.
However, we can give ourselves a bit more flexibility by choosing one specific bit of
data and matching it using `matchesJsonPath`.
Let's say that if we receive a specific contact ID then we'll trigger the error.
To do this, change the body match type to `matchesJsonPath` and the expression to
`$.contact.id` `equalTo` `666`:
Finally, change the response status code to `503`, and let's also add a plain text
error message supported by a `Content-Type: text/plain` header:
### Testing the error response
Now we can send a test request and see the error response returned:
## Matching the request body with XML equality
When dealing with request bodies that are small and have no data of a transient nature (e.g. transaction IDs or today's date)
`equalToXml` is a straightforward way to specify a match.
For instance given a SOAP service for managing a to do list, you may wish to mock an interaction matching a specific request to add an item:
Which returns a success response:
Testing this returns the expected XML response:
## Matching the request body with XPath
When working with large SOAP requests `equalToXml` can become quite slow as it must perform a comparison on every node in the XML document.
It's often faster to match specific elements within the document using the `matchesXPath` operator,
and since this is a much looser approach to matching it's another way to solve
the problem described above where frequently changing values are present.
When matching using XPath, your aim should be to target as few elements/attributes as possible while being able
to reliably distinguish between requests.
Given the same request body as in the previous section, we could use the following
XPath to match just on the value of the `m:ToDoItem` element:
```xpath
//AddToDoItem/ToDoItem[text()='Have a wash']
```
### Using multiple XPath expressions
Sometimes you need to match on more than one XML element to be able to adequately
distinguish between requests. Although XPath supports multiple predicates with logical and/or,
often it can be easier to use multiple body matchers each targeting a single element.
Suppose we added a `UserId` field that we also wanted to target:
```xml
### A gotcha - the recursive selector: //
Given the above XML document, you might expect the following XPath expression to
produce a match:
```xpath
//UserId[text()='abc123']
```
However, due to a quirk of how XML documents with namespaces are evaluated this won't work.
Ensuring that you select at least one node beneath the element searched for recursively
will fix this, so the above XPath can be corrected like this:
```xpath
//UserId/text()[.='abc123']
```
### Simulating gRPC services
Source: https://docs.wiremock.io/grpc/overview
WireMock Cloud enables you to mock your gRPC APIs in a similar fashion to a general HTTP/HTTPS mock API.
Incoming gRPC messages are converted to JSON for the purpose of request matching and templating.
JSON responses are also converted to gRPC messages before being sent to the client.
## Usage
### Creating a gRPC mock API
To create a gRPC mock API, select the gRPC API template on the mock API creation page and give it a name (and optional
custom hostname) of your choosing.
### Uploading a descriptor set file
Once your API is created, the first step to take before you can configure your stubs is to upload a gRPC descriptor set
file that describes your gRPC services, methods and messages.
Navigate to your mock API's gRPC page and select a file from your file system to upload.
See [generating a descriptor set file](#generating-a-descriptor-set-file) for details of how to obtain a descriptor set.
### Configuring gRPC stubs.
Once you've successfully uploaded your descriptor set file you can create stubs for your gRPC API.
The stub form for a gRPC mock API is similar to a general HTTP/HTTPS mock API with a few key differences.
Firstly, each gRPC stub must be associated with a particular service and method defined in the uploaded descriptor set
file.
Request matching for gRPC stubs is limited to body matchers.
Additionally, body matchers are constrained to only JSON related matchers (e.g. "equals JSON", "matches JSONPath").
Response statuses can be configured to any valid gRPC status.
Response bodies must return valid JSON that conforms to the gRPC method's response message.
For example, given a descriptor set file that was generated from the following proto file:
```protobuf
syntax = "proto3";
service BookingService {
rpc booking(BookingRequest) returns (BookingResponse);
}
message BookingRequest {
string id = 1;
}
message BookingResponse {
string id = 1;
string created = 2;
repeated Participant participants = 3;
}
message Participant {
string name = 1;
}
```
The stub response body for the `booking` method would look something like the following:
```json
{
"id": "123",
"created": "2024-08-13T10:12:00",
"participants": [
{
"name": "Bob"
},
{
"name": "Alice"
}
]
}
```
When the response status of your stub is set to a non `OK` status, the response body is not used and a `Status Reason`
must be provided.
An example response body is generated for your stub after selecting the service and method, to help guide the shape of
your responses.
An example request body is also generated for JSON equality body matchers that you add to your stub.
### Testing your stubs
Like with traditional mock APIs, gRPC mock APIs come with a test requester built into the WireMock Cloud app.
This test requester can be used to make real gRPC requests to your mock API via a simple interface.
To use the test requester, make sure to navigate to the gRPC mock API you wish to test in WireMock Cloud, then open the
Test Requester tab on the right side of your browser window.
Select the service and method that you want to make a request to, add any headers you want to include and supply a
request body, if desired.
After clicking "Send" to perform the request, the response will be displayed, including the status and body.
You will also be able to view this request in your mock API's request log page.
A handy "Copy gRPCurl command" button is also provided by the test requester that allows you to make a similar request
using the popular [gRPCurl CLI tool](https://github.com/fullstorydev/grpcurl).
Clicking this button will copy a gRPCurl command to your clipboard that you can then paste into your favourite terminal
to execute (provided you have gRPCurl installed).
## Generating a descriptor set file
To generate a descriptor set file from your proto file, simply add the `--descriptor_set_out` option to your protoc
command.
For example,
```bash
protoc --descriptor_set_out my-api.dsc MyApi.proto
```
### Simulating GraphQL APIs
Source: https://docs.wiremock.io/graphql/overview
As well as REST, SOAP and gRPC support, WireMock Cloud has native support for mocking your GraphQL APIs.
Out of the box, GraphQL mock APIs will respond with generated mock data for any valid GraphQL queries, and more
fine-grained control over response data can be added with ease.
## Usage
### Creating a GraphQL mock API
To create a GraphQL mock API, select the GraphQL API template on the mock API creation page and give it a name (and
optional custom hostname) of your choosing.
### Uploading a schema
Once your API is created, the first step to take before you can configure your stubs is to upload a GraphQL schema that
describes the operations you want to perform with your mock API.
Navigate to your mock API's GraphQL page and select a schema file from your file system or paste a schema directly into
the schema text field.
An example of a very simple GraphQL schema for querying user data is provided below:
```graphql
type Query {
user(id: ID): User
users: [User]
}
type User {
id: ID
name: String
dob: String
enabled: Boolean
loginCount: Int
hobbies: [String]
}
```
From this page, you can edit your API's schema at any time.
### Querying your mock API
Now that your mock API has a schema to work with, it can automatically respond to any valid GraphQL query it receives
that matches the schema.
The simplest way to start querying your mock API is via the [Apollo Sandbox](https://studio.apollographql.com/sandbox/explorer),
but any spec compliant GraphQL client will work.
To start querying your mock API using [Apollo Sandbox](https://studio.apollographql.com/sandbox/explorer), copy your
mock API's base URL into the sandbox endpoint input.
Once the sandbox is pointing at your mock API, it should pick up the API's schema and present a helpful interface for
constructing queries. Construct a query, either by writing one manually or with the help of the sandbox's documentation
interface, then execute the query. You should see a matching response that contains generated mock data. Executing the
query multiple times should return new data each time.
### Configuring the default GraphQL stub
As we've seen, the default behaviour for a GraphQL mock API is to respond to valid queries with automatically generated
mock data.
This behaviour is defined by a default stub that is added to all GraphQL mock APIs on creation.
You can view this stub on the Stubs page of your mock API.
Out-of-the-box, this stub will attempt to serve any HTTP request the API receives, regardless of HTTP method or path.
The stub expects the request to contain a GraphQL query, either in the request query parameters for `GET` requests, or
the request body for all other request methods.
More detail on the request query format can be found on [the official GraphQL site](https://graphql.org/learn/serving-over-http/#methods).
If the request query is valid and matches [the API's schema](#uploading-a-schema), the stub will respond with a 200
status and a JSON payload with [the standard GraphQL response body format](https://graphql.org/learn/serving-over-http/#body).
If you want more control over the format of the data that this default stub generates, there are a few configuration
options available for GraphQL's built-in types.
String and ID values can be configured to always return a fixed value, values with a minimum and/or maximum length, or
values that match a given regular expression pattern, such as `[A-F0-9]+` (a string of one or more random characters
between `A` and `F` or `0` and `9`) or `(enabled|disabled)` (either `enabled` or `disabled`).
Int and float values can be configured to only return values above a minimum and/or below a maximum.
An additional option is available for floats that sets the scale of all float values (i.e. the number of digits to the
right of the decimal point). For example, in the number `123.45`, the scale is `2`. The default scale is `2`.
Boolean values can be fixed to always return `true` or always return `false`.
Lists can be configured to always return a fixed amount of items. The default is `3`.
### Configuring custom GraphQL stubs
The default GraphQL stub is a great starting point for configuring your mock API, but often we want more control over
the data our mock API returns for a given query.
That's where creating and configuring our own stubs comes in.
Custom stubs allow your mock API to match on specific GraphQL queries and return static or dynamic responses to those
requests.
To match on a specific query, enter a valid GraphQL query into the `Match query` field of your stub.
When matching, the GraphQL query matcher retrieves a request's query (either from the query parameters for `GET`
requests, or from the request body for other request methods) and check if it is [*semantically* similar](#semantic-query-matching)
to the expected query.
If it is, this will be considered a match.
To return a specific response body, enter this into the `Response body` field as usual.
If you want to return a valid GraphQL response body in JSON format, you'll need to specify the full JSON, including
the root fields (i.e. `"data"`, `"errors"`, `"extensions"`), [as outlined in the GraphQL official documentation](https://graphql.org/learn/serving-over-http/#body).
[Dynamic response templating](/response-templating) is available for GraphQL stubs, like all other API types.
### Converting request logs to stubs
The simplest way to create a stub with some pre-configured data is to navigate to an existing request in your mock
API's Request Log and click the `Convert to stub` button at the bottom of the page.
This will create a new stub in your mock API with a query matcher containing the same query that was sent in the
original request, as well as a response body that matches the one returned to that request.
From here, you can customize your stub to suit your needs.
## Semantic query matching
Similar to WireMock Cloud's JSON equality matcher, WireMock Cloud's GraphQL query matcher performs semantic comparison
when checking if a request's query matches the expected query.
This means that the ordering of a query's fields, arguments, etc. is irrelevant.
For example, the two queries below would be considered a semantic match:
```graphql
query GetPosts { posts(limit: 20, offset: 60) { id name } }
```
```graphql
query GetPosts { posts(offset: 60, limit: 20) { name id } }
```
### Ignoring unused definitions
Additionally, schema definitions (SDL) and unused operations are ignored when comparing two queries.
For example, consider the two queries below:
```graphql
query GetUser { user(id: 123) { id } }
type User { id: ID }
```
```graphql
query GetUser { user(id: 123) { id } }
query GetUsers { users { id username } }
union StringOrBool = String | Boolean
schema { query: Query }
```
When these two queries are compared, the SDL definitions (i.e. `type User`, `union StringOrBool` and `schema`) will
always be ignored.
As for the queries, only the query operation that was specified in the request will be compared.
If the supplied operation name for the request was `GetUser`, the two queries would be considered a match, as the only
part being compared would be
```graphql
query GetUser { user(id: 123) { id } }
```
However, if the supplied operation name was `GetUsers`, the two queries would not be considered a match, as the first
query does not even contain an operation with that name.
### Variable resolution
When a request uses variables in its query, these variables are resolved *before* matching is performed.
This means that the names of variables and their definitions are irrelevant when matching.
Only their resolved values, supplied in the request, are relevant.
For example, consider the following queries:
```graphql
query GetUser { user(id: 123) { id } }
```
```graphql
query GetUser($userId: ID) { user(id: $userId) { id } }
```
When comparing these two queries, the variable definition (`$userId: ID`) will be removed, and all references to this
variable (e.g. `id: $userId`) will be replaced with the value of `$userId` supplied by the request.
So, if the request's variables looked like
```json
{ "userId": 123 }
```
then the second query defined above would resolve to
```graphql
query GetUser { user(id: 123) { id } }
```
which is identical to the first query, so would be considered a match.
Note that variable resolution is performed on both the expected query and the request query.
Therefore, it's possible to specify that a particular value in a query is irrelevant by using a variable reference for
that value in both the expected query and request query.
For example, the following query will always match itself, regardless of what the `$userId` variable resolves to.
```graphql
query GetUser($userId: ID) { user(id: $userId) { id } }
```
Variable defaults (e.g. `$userId: ID = 321`) will be used if no variable is supplied in the request.
If a variable is defined in the query, but is not supplied by the request and does not have a default value, the
variable's value will resolve to `null`.
## GraphQL Validation
Validation settings can be used to ensure that requests made to your mock API and responses returned by your mock API
are compliant with your GraphQL schema, as well as [the GraphQL specification](https://spec.graphql.org/draft/).
Settings for GraphQL validation can be found on the GraphQL page of your mock API.
There are three options for GraphQL validation: no validation (the default), soft validation, and hard validation.
The "No validation" option will have no effect on your mock API.
Enabling soft validation will cause non-compliant requests to contain validation warnings in your mock API's request log.
Any request to the mock API and/or any response returned by the mock API containing data/attributes that do not conform
to the GraphQL spec or the mock API's GraphQL schema will be highlighted on the request log page.
Details of how the request/response was invalid can also be viewed in the request log.
Enabling hard validation will cause the same request log behavior as soft validation, with the added functionality of
returning `4xx`/`5xx` error responses containing details of validation issues.
## Current limitations
There are certain features that are not yet supported by GraphQL stubs:
* [Advanced stubbing](/advanced-stubbing)
* [Webhooks](/webhooks)
* [Chaos testing](/chaos)
* [Response delays](/delays)
* [Proxying requests](/proxying)
* [API rate limits](/user-rate-limits)
As well as additional GraphQL specific matchers and template helpers.
If you have feedback or questions on our GraphQL functionality as it evolves, we'd love to hear from you.
Please [get in touch](mailto:support@wiremock.io).
### Simulating federated GraphQL APIs
Source: https://docs.wiremock.io/graphql/federation
GraphQL Federation is an architectural pattern that allows multiple, independently managed GraphQL APIs (called
"subgraphs") to be combined and queried from a single, overarching GraphQL API (called a "supergraph").
WireMock Cloud provides support for GraphQL Federation, allowing your GraphQL mock APIs to be used as subgraphs.
## Usage
To enable GraphQL Federation in your GraphQL mock API, click the Federation toggle on the GraphQL page of your mock API.
Enabling Federation will add the appropriate federation fields to your GraphQL schema that an Apollo Federation
supergraph requires to make calls to your subgraph.
It also ensures that data returned by [mock data generation stubs](/graphql/overview#configuring-the-default-graphql-stub)
is compliant with the entity queries supplied by the supergraph.
Now that Federation is enabled, you can upload a Federation compliant GraphQL schema to your mock API.
Once your subgraph mock API is ready, point your supergraph at this subgraph and start making requests to the supergraph.
Your supergraph will begin making calls to your subgraph to retrieve the requested data.
To add more subgraph mocks to your supergraph, create multiple GraphQL mock APIs and repeat the above steps in each.
## Usage Example
Below is a simple example showcasing how to set up some GraphQL mock subgraphs in WireMock Cloud, and query them from a
supergraph running on your local machine.
This example uses [Apollo's Rover CLI tool](https://www.apollographql.com/docs/rover) to run a supergraph locally.
If you want to try out this example yourself, ensure that you have Rover installed on your machine.
More information on installing Rover can be found [here](https://www.apollographql.com/docs/rover/getting-started).
First, we need to configure some subgraphs to point our supergraph at.
We'll set up three subgraph mock APIs in WireMock Cloud: a `users` subgraph, a `products` subgraph and a `review`
subgraph.
The schemas for each subgraph are below:
import UsersGraphQl from '/snippets/users.graphql.mdx';
import ProductsGraphQl from '/snippets/products.graphql.mdx';
import ReviewsGraphQl from '/snippets/reviews.graphql.mdx';
In the Response section, set HTTP status, headers and body text. Typically it is a good idea to send a `Content-Type` header in HTTP responses, so add one by clicking New Header and setting `Content-Type` to `application/json`.

Hit Save, then you're ready to test your stub. Point your browser to `http://
For quick reference, here are the options available to you:
* **_Equals_** - matches if the request body is equal to the expected body
* **_Matches Regex_** - matches if the request body matches the specified regex
* **_Does Not Match Regex_** - matches if the request body does not match the specified regex
* **_Contains_** - matches if the request body contains the expected body
* **_Equals XML_** - matches if the request body is equal to the expected XML
* **_Matches XPath_** - matches if the request body matches the specified XPath
* **_Equals JSON_** - matches if the request body is equal to the expected JSON
* **_Matches JSONPath_** - matches if the request body matches the specified JSONPath
* **_Matches JSON Schema_** - matches if the request body matches the specified JSON schema
* **_Is Absent_** - matches if the request body is absent
**Note** that the `NOT` checkbox can be used to negate the selected matcher.
## Request method matching
The HTTP method that required for this stub to match. This defaults to `ANY`, meaning that a request with any method
will match.
## Request priority matching
Requests of a higher priority (i.e. lower number) will be matched first, in cases where more than one stub mapping in the
list would match a given request.
Normally it's fine to leave the priority at its default. However it can sometimes be useful to so create a low priority,
broadly matching stub defining some default behaviour e.g. a 404 page, and then create a set of higher priority, more specific
stubs for testing individual cases. See [Serving Default Responses](/default-responses/) for more details.
## URL matching
Determines how the URL will be matched. The options are:
- **Path and query** - exactly matches the path and query string parts of the URL
- **Path and query regex** - matches the path and query string parts of the URL against a regular expression
- **Path** - exactly matches the path part of the URL
- **Path regex** - matches the path part of the URL against a regular expression
- **Any URL** - matches any URL
## Advanced - Query parameters, headers and more
In addition to the URL and body, requests can be matched on:
- Headers
- Query parameters
- Cookies
Parameter match clauses can use the same set of match operations as body clauses:
It's usually a good idea to use path only URL matching with query parameter matches.
When multiple match clauses are added a request must match all of them for the response to be served (they are combined
with logical AND).
### Logical AND OR matchers
You can build complex logic using AND OR operators for Headers, Query parameters, Cookies, Form parameters and Path parameters.
These operators can be nested to help build realistic matching logic into your stubs.
## Matching JSON request bodies
Two specific match types exist for JSON formatted request bodies: equality (`equalToJson`) and JSONPath (`matchesJsonPath`).
### Equality
`equalToJson` performs a semantic comparison between the incoming JSON and the expected value, meaning that
it will return a match even when, for instance, the two documents have different amounts of whitespace.
You can also specify that array order an additional elements in the request JSON be ignored.
### JSON Placeholders
JSON equality matching is implemented by [JsonUnit](https://github.com/lukas-krecan/JsonUnit), and
therefore supports placeholder syntax, allowing looser specification of fields within the document.
For instance, consider a request body like this, where `transaction_id` is unique to
each request:
```json
{
"event": "details-updated",
"transaction_id": "abc-123-def"
}
```
Requiring an exact match on this document would ensure no match could ever be made, since
the same transaction ID would never be repeated.
This can be solved using a placeholder:
```json
{
"event": "details-updated",
"transaction_id": "${json-unit.ignore}"
}
```
If you want to constrain the value to a specific type or pattern the following placeholders are also valid:
- `${json-unit.regex}[A-Z]+` (any Java-style regular expression can be used)
- `${json-unit.any-string}`
- `${json-unit.any-boolean}`
- `${json-unit.any-number}`
### JSONPath
`matchesJsonPath` allows request bodies to be matched according to a [JSONPath](https://github.com/json-path/JsonPath) expression. The
JSONPath expression is used to select one or more values from the request body, then the result is matched against sub-matcher (`equal to`, `contains` etc.).
It is also possible to simply assert that the expression returns something, by selecting `is present` from the list.
The expression in the above screenshot (`$.event` `equal to` `description-updated`) would match a request body of
```json
{
"event": "description-updated"
}
```
but not
```json
{
"event": "document-created"
}
```
## Matching XML request bodies
As with JSON matching, there are two match types available for working with XML: `equalToXml` and `matchesXPath`.
### Equality
`equalToXml` performs a semantic comparison between the incoming and expected XML documents, meaning that it will return a match regardless of whitespace, comments and node order.
### XML placeholders
When using `equalToXml` it is possible to ignore the value of specific elements using [XMLUnit](https://github.com/xmlunit/user-guide/wiki/Placeholders)'s placeholder syntax. For instance if you
expected to receive an XML request body containing a transaction ID that changed on every request you could ignore that value like this:
```xml
### XPath
`matchesXPath` allows XML request bodies to be matched according to an [XPath](https://www.w3schools.com/xml/xpath_syntax.asp) expression.
For instance, an XML request body like
```xml
## Response body
A response body can optionally be specified. If [response templating](/response-templating/)
is enabled, certain parts can be dynamically generated using request attributes and random data.
### Dynamic Responses with Templates
Source: https://docs.wiremock.io/response-templating/basics
Some elements of WireMock Cloud stub responses can be configured generated dynamically, via the use of [Handlebars templates](https://github.com/jknack/handlebars.java). This builds on the same templating system documented in [WireMock OSS's response templating docs](https://wiremock.org/docs/response-templating/).
Most commonly this is used in the response body but response header values can also
be templated. For proxy responses, the target URL can be a template.
## Enabling templating
Enable templating for a stub by ticking the "Enable templating" box in the Response section:
Ticking this box means that header values can be templated e.g.
And also the response body e.g.
## Handlebars overview
A complete description of the Handlebars syntax and core helpers can be found on the [Handlebars JS](https://handlebarsjs.com/guide/), but we'll cover the essentials here.
Handlebars works like many other template languages - a template is provided a data model
and uses a special tag syntax to denote dynamic elements, referred to as a "helper" in this case.
Helpers are always delimited by double or triple curly braces (`{` and `}`). In the simplest case a helper can
simply output the value of a variable in the model:
```handlebars
{{myVariable}} // Top-level model variable
{{outerVar.innerVar}} // Nested model variable
```
### Helper parameters
Helpers can take both positional and named parameters. In both cases they are delimited by spaces.
The following helper takes three positional parameters -
the string in which the replacement should take place, the substring to find and the
replacement value:
```handlebars
{{replace myString 'foo' 'bar'}}
```
Named values are of the form `name=value`. The following helper has a single
positional parameter followed by a parameter named `format`:
```handlebars
{{dateFormat myDate format='yyyy-MM-dd'}}
```
### Nesting helpers
Sometimes it's necessary to apply a helper to the result of another one. This can
be achieved by nesting helpers using bracket syntax. For example, this template
will truncate the input string, then capitalise the first letter:
```handlebars
{{capitalize (substring myString 0 4)}}
```
### Blocks
Blocks can be used to apply processing to an inner piece of content.
```handlebars
{{#if productExists}}
// do something with the product
{{else}}
// product not found
{{/if}}
```
Blocks form the foundation of logical and looping structures in Handlebars and are [described here in more detail](/response-templating/conditional-logic-and-iteration/).
### HTML escaping
We mentioned earlier that double or triple curly braces are used to delimit helpers.
The difference between these two forms is that with double braces, Handlebars will
automatically HTML escape the output of the helper, whereas with triple braces no escaping will be
applied.
For instance, suppose we have a data model where the variable `tag` has the value ``.
The template
```handlebars
{{tag}}
```
will output
```
<html>
```
whereas the template
```handlebars
{{{tag}}}
```
will output
```
```
## The request model
When templates are evaluated, they have access to a data model containing information about the incoming request. For a complete reference of all available request attributes and how to access them, see the [Request Model Reference](/response-templating/request-model).
## Handlebars helpers
WireMock Cloud provides a set of Handlebars helpers that perform a variety of logical functions and transformations inside templates. These include all of the standard helpers from the [Java Handlebars implementation by jknack](https://github.com/jknack/handlebars.java).
All of the available helpers are described in detail in these articles:
* [Conditional Logic and Iteration](./conditional-logic-and-iteration/)
* [Strings](./string-helpers/)
* [String Encodings](./string-encodings/)
* [Dates & Times](./dates-and-times/)
* [Random Values](./random-values/)
* [Random Faker](./random-faker/)
* [XML](./xml/)
* [JSON](./json/)
* [JSON Web Tokens](./jwt/)
* [Miscellaneous Helpers](./misc-helpers/)
### Using a JWT from the Request in a Response Template
Source: https://docs.wiremock.io/response-templating/using-jwt-claims-from-request
Many APIs receive a [JSON Web Token (JWT)](https://jwt.io/) from the client, often as a bearer token or in a custom
header, and are expected to tailor their response based on the claims it contains. This guide shows how to extract a
JWT from an incoming request and use its claims when building a templated stub response.
In the Response section, set the Status to `403` and the body content to `"Sorry, you can't do that"`.
Create a second stub with the method set to `GET`, the URL to `/examples/12` and the response body to `"Example 12 body"` (keeping the Status as `200`).
Now if you make a request that matches the specific stub you will see a response with a `200` status:
Once you have added a webhook to your stub, you can configure each attribute of the request that will be sent when the
webhook is triggered, including the request method (e.g. `POST`, `GET`, `PUT`), URL, headers, and body.
A delay can also be set on the webhook, in the same fashion as [response delays](/delays), to stop the webhook's
requests from firing until some time after the triggering request is received.
### Templating
The request URL, header values and body attributes of a webhook can all be [templated](/response-templating), allowing
for request attributes to be set dynamically using the content of the triggering request, as well as other contexts like
[dynamic state](/dynamic-state) and [data sources](/data-sources).
All data and helpers that are available to the response body template are also available to the webhook request
attribute templates, **with the caveat that the triggering request is referenced by `originalRequest`, rather than
`request`.**
## Observing webhooks
All webhook request and responses are logged as events under the request that triggered them, and can be viewed in your
mock API's request log page.
## Asynchronous timing
Webhooks are fired asynchronously, outside the lifetime of the request that triggered them, so may not have completed by
the time the triggering request has completed.
There is also no guarantee of the order that webhooks will be fired if multiple webhooks are configured on a stub.
### Proxying
Source: https://docs.wiremock.io/proxying
When working with an existing API it can be useful to pass some requests through to it for testing, while
serving stubbed responses for others.
For instance, if an API is not yet fully implemented then testing progress can still be made
for the calling application by stubbing the parts not yet completed.
Additionally, proxying all but a selection of requests enables testing of edge and failure cases that would be hard to
replicate predictably in the target API.
## Usage
Proxying is configured per-stub. When a stub is configured to serve a proxy response, all of the normal request matching rules
apply, but instead of returning a canned response, the request is forwarded to the target.
Proxying is enabled by selecting the Proxy tab in the stub's Response section and completing (at a minimum) the base URL field.
Additional request headers can optionally be specified. These will be added to the proxy request if not already present,
or will override the existing value if present.
The relative part of a request's URL will be appended onto the base URL, so given a proxy base URL of `http://my-site.com/base`, a
request made to `http://my-mock-api.wiremockapi.cloud/things/1` would result in a proxy request to `http://my-site.com/base/things/1`.
## Templating the base URL
When the Enable templating check box is ticked, the base URL can be a handlebars template, meaning that properties from the
incoming request can be used to determine the URL. See [Response Templating](/response-templating/basics/) for details of the
model and syntax used.
## Hostname rewriting
Often API responses contain absolute links and other content that refers to the domain name of the API's origin.
When proxying to another API this can be undesirable as the mock API's domain is different from the proxy target and thus a client following such a link would make its next request directly to the proxy target rather than the mock API.
To remedy this issue we can enable hostname rewriting, which will replace any instances of the proxy target's domain name in the response headers or body with the mock API's domain name.
For instance, if we configured a stub in a mock API `https://my-mock-api.wiremockapi.cloud` to with a proxy target of `https://api.github.com` and a proxied response body contained `"self": "https://api.github.com/users/123"`, with hostname rewriting enabled this would be changed to `"self": "https://my-mock-api.wiremockapi.cloud/users/123"`.
## The proxy/intercept pattern
It is often desirable to proxy requests by default while stubbing a few specific cases. This can be achieved using a variation
of the [Default Responses](./default-responses/) approach.
In summary, the proxy stub is created to be the default, with broad request matching criteria and a low priority value. Then
individual stubs are created at higher priorities with specific request URLs, bodies or anything else distinguishing.
Examples of things these specific stubs can be used for are:
* Return an HTTP 503 response
* Return response data in a format not expected by your app's client
* Close the connection prematurely without sending a response (see [Simulating Faults](./simulating-faults/))
### Response Delays
Source: https://docs.wiremock.io/delays
Calls over a network to an API can be delayed for many reasons e.g. network congestion or excessive server load. For applications
to be resilient they must be designed to cope with this inevitable variability, and tested to ensure they behave as expected
when conditions aren't optimal.
In particular it is important to check that timeouts work as configured, and that your end user's experience is maintained.
WireMock Cloud stubs can be served with a fixed or random delay, or can be "dribbled" back in chunks over a defined time period.
## Fixed delay
A fixed delay straightforwardly adds a pause for the specified number of milliseconds before serving the stub's response.
## Random delay
Random delay adds a random pause before serving the response. Two statistical distributions are available:
### Uniform
### Log normal
## Chunked dribble delay
Chunked dribble delay flushes the response body out in chunks over the total defined period:
## Delays and proxying
Fixed or random delays can be added to proxy responses in addition to direct responses, however chunked delays cannot at present.
### User Configurable Rate Limits
Source: https://docs.wiremock.io/user-rate-limits
You can configure your own rate limiters and apply them to your stubs, allowing
you to simulate the real-world rate limiters protecting the APIs you're mocking.
## Add rate limits to a mock api
Rate limits are defined in your mock api settings page.
You can choose one of your rate limits to be the default rate limit for the mock API, which means it will apply to all stubs, unless a different rate limit is selected for a specific stub.
Once created rate limit names cannot be changed as then name is used as the unique identifier
when assigning to a stub.
If you would like to update the name please create a new rate limit
and attached to the new rate limit to your stub.
## Add rate limit to a stub
Rate limits can be applied to a stub in the "Response" section.
Stubs will by default have either no rate limit, or the default rate limit selected at the API level.
Even if the API has a default rate limit, you can selected another of your previously created rate limits to allow for any individual stub to perform with a rate limit other than the default.
## Creating a rate limiter via API
A rate limiter is defined by an object in your mock API's settings document. The
JSON attribute key is then used to apply the rate limiter to specific stub mappings.
A rate limiter has two mandatory parameters:
* `unit` - the time unit the rate is being expressed in e.g. `nanoseconds`, `seconds`, `minutes`
* `rate` - the number of requests per the time unit permitted e.g. `15`
You can also optionally allow bursting by setting:
* `burst` - the number of requests that can be made in a burst over the set rate limit
You set the rate limit by making a `PUT` request to `https://
### Chaos settings - Basics
Source: https://docs.wiremock.io/chaos
The idea of the chaos settings is to introduce an element of failure into your
environment and observe how clients cope with it.
WireMock Cloud now allows introducing a random element of chaos across all the
calls to a particular API. This would allow you to check that your client
behaves appropriately; closes resources correctly, times out correctly, conveys
sensible error messages to the end user and to your monitoring systems, perhaps
opens circuit breakers to take load off the upstream system or other resilience
mechanisms.
## Enabling Chaos
You enable chaos by toggling the "Enable chaos" switch.
Once chaos is enabled, you can set a percentage of requests to that API to
experience a failure using the slider, or type it directly.
The configured percentage of failures will be distributed evenly among the
failure modes.
We support five failure modes:
### [Socket close](#socket-close)
A request will just have the socket closed, with no data returned to the client
at all. This would allow you to check that your client closes all resources
appropriately in response.
### [Socket reset](#socket-reset)
The server will close the connection, setting `SO_LINGER` to 0 and thus
preventing the `TIME_WAIT` state being entered. Typically causes a
"Connection reset by peer" type error to be thrown by the client.
Note: this only seems to work properly on \*nix OSs. On Windows it will most
likely cause the connection to hang rather than reset.
This would allow you to check that your client closes all resources
appropriately in response.
### [Invalid HTTP](#invalid-http)
The server will start by responding with a valid HTTP status line, then will
return random bytes, so an invalid HTTP response. Then it will close the
connection.
### [Long delay](#long-delay)
The server will delay for the configured amount of time before responding. This
would allow you to check that you have appropriately configured timeouts.
### [HTTP Error status](#http-error-status)
The server will return valid HTTP responses with the configured error status
codes.
### Data Sources - Using External Test Data
Source: https://docs.wiremock.io/data-sources/overview
WireMock Cloud provides the ability to use your own test data in your mock APIs, when both matching and rendering responses.
## Usage
To use a data source, it must be [attached](#attaching-a-data-source-to-a-stub) to one (or more) stub(s) of a mock API.
Data sources have two primary functions when attached to a stub mapping:
- [Custom stub matching](#custom-stub-matching) based on the result of a configurable query
- [Providing data](#rendering-data-in-response) to be used in a stub's [response template](/response-templating/basics).
### Attaching a data source to a stub
Once your data source has been set up correctly, following the steps in [creating a CSV data source](./managing-csv-data-sources),
or [creating a database data source](./managing-database-data-sources) it can be attached to a stub.
To attach a data source to a stub in WireMock Cloud, navigate to the desired stub and open the "Data source" section.
Select the data source you wish to attach from the dropdown list.
Enter a `WHERE` clause, or leave blank. The `WHERE` clause allows you to use `ORDER BY`, `LIMIT` and `OFFSET` to get
consistent ordering and pagination.
Once saved, your data source is now attached to your stub and will be used when [matching incoming requests](./overview#custom-stub-matching) and [rendering responses](./overview#rendering-data-in-response).
#### Deleting a data source from a stub
If you no longer wish for your stub to have the capabilities provided by data sources, you can detach/delete the data source from the stub at any time.
To detach a data source from a stub, simply open the "Data source" section of the desired stub and click the delete button, then save.
#### Which stubs can reference attached data sources?
Once a data source has been created, it can be used by all stubs within the organization.
However, a stub can only have a single data source attached to it at a time
### Custom stub matching
Attaching a data source to a stub allows the stub to only match a request when the data source returns non-empty data.
The data that a data source returns for a given request and stub can be filtered via a configurable ANSI standard SQL query.
This query is attached to a stub alongside the data source.
This query acts as the `WHERE` clause of a standard SQL statement that is executed on the data source.
The columns of a data source can be queried as if they were columns of an SQL table.
For instance, if your data source has an "age" column of type `INTEGER`, you can retrieve all rows where age is greater than twenty-five using the query `age > 25`.
Each data source column type maps to an SQL column type:
| Data source type | SQL type |
|-----------------------------|----------------------------|
| `BOOLEAN` | `BOOLEAN` |
| `DECIMAL` | `FLOAT` |
| `INTEGER` | `INTEGER` |
| `STRING` | `VARCHAR` |
| `DATE` | `DATE` |
| `TIME` (time zoned) | `TIME WITH TIME ZONE` |
| `TIME` (not time zoned) | `TIME` |
| `DATETIME` (time zoned) | `TIMESTAMP WITH TIME ZONE` |
| `DATETIME` (not time zoned) | `TIMESTAMP` |
All standard SQL operators of each type are supported in the attached query (e.g. `+`, `-`, `=`, `<`, `>`, `AND`, `OR`, `EXISTS`, `BETWEEN`, etc.).
#### Handlebars templating in query
The data source query supports handlebars templating in order to dynamically create queries based off the contents of an incoming request.
The model available in the template is [the same request data model that is provided in the response template](/response-templating/basics/#the-data-model).
For example, if your data source contains a "first_name" column, you can filter the data source via a query parameter provided in the request like so: `first_name = '{{request.query.name}}'`.
When a request is sent to the mock API with a `name` query parameter, the value of this parameter will be inserted into the `WHERE` clause.
So a query string that contains `name=alice` will result in a `WHERE` clause of `first_name = 'alice'`.
#### Potential pitfalls
As in standard SQL, to reference a column whose name contains whitespace or starts with a digit, the column name must be surrounded by double quotes (e.g. `"first name" == 'bob'`).
Quoting a column name also enforces case sensitivity (i.e. the casing in the query must match the casing of the column name exactly).
Currently, only simple `WHERE` clause expressions that are part of the ANSI standard SQL specification are supported including
`ORDER BY`, `LIMIT` and `OFFSET`. Sub-queries are not officially supported.
An empty query will return the entirety of the data source.
Thus, the stub's data matcher will always return a match, as long as the data source itself is not empty.
#### Disabling matching
This matching functionality can be disabled via a checkbox.
When disabled, no matching based on the returned data will be performed.
In other words, if all other matchers of a stub return a match for a particular request, the stub will be considered a match, even if the data source returned no data.
In this scenario, the available data items in the [response template](#rendering-data-in-response) will be an empty list.
### Rendering data in response
Attaching a data source to a stub allows the data contained in the data source to be rendered in the response via [response templating](/response-templating/basics).
The data available from the data source for a particular request's response is the result of evaluating the stub's [data source query](#custom-stub-matching) for that request.
For instance, if a stub is configured with a query of `age > 25`, then the data available in the response template will be limited to all rows whose "age" column exceeds twenty-five.
This data can be referenced in the response template via the `data.items` property.
This property is a list of all the rows returned by the data source query.
For example, to render a JSON array of the name of each returned row, the following response template could be used:
```handlebars
[
{{~#arrayJoin ',' data.items as |item|~}}
{
"id": {{item.id}},
"name": "{{item.name}}"
}
{{/arrayJoin}}
]
```
As well as iterating over the entire result list, rows can be referenced by their individual index (e.g. `{{ data.items.0.name }}'`).
#### Potential pitfalls
Field names containing whitespace or starting with a digit must be surrounded by square brackets.
For example, a column with the name "first name" would be referenced like so: `{{ data.items.0.[first name] }}'`.
Supplying an empty query will provide the entirety of the data source to the template model.
### Creating & Editing CSV Data Sources
Source: https://docs.wiremock.io/data-sources/managing-csv-data-sources
## Creating a CSV data source
Data sources can be created at the organisation level, meaning that the Data sources you create can be shared among the
members of your organisation.
To create a data source:
- Navigate to the Data Sources page.
- Click on the button, `+Create new data source`.
- Choose `CSV based` from the dropdown and select the CSV file containing your data.
- Provide a name for your data source.
- Click `save` at the bottom of the page.
## Editing a CSV data source
Data sources can be updated after creation.
To edit a data source:
- Navigate to the Data Sources page.
- Click on the data source you wish to edit, from the list provided.
- Update your data source.
- Click on the `save` at the bottom of the page.
Once in the data source page, you will be able to:
- Replace the csv file
- Rename the data source
- Change the column types
## Columns
### Column names
When uploading the CSV file, please ensure the following requirements for the column names:
- Column names must be unique within the CSV file.
- Column names must be between 1 and 128 characters in length.
- Column names can only contain letters, digits, the underscore character and spaces, and must not start with an
underscore.
- Column names cannot be any of the following reserved keywords:
`all`, `and`, `any`, `array`, `as`, `at`, `between`, `both`, `by`, `call`, `case`, `cast`, `check`, `coalesce`, `constraint`, `convert`, `corresponding`, `create`, `cross`, `cube`, `default`, `distinct`, `do`, `drop`, `else`, `every`, `except`, `exists`, `fetch`, `for`, `foreign`, `from`, `full`, `grant`, `group`, `grouping`, `having`, `in`, `inner`, `intersect`, `into`, `is`, `join`, `leading`, `left`, `like`, `natural`, `not`, `nullif`, `on`, `or`, `order`, `outer`, `primary`, `references`, `right`, `rollup`, `select`, `set`, `some`, `sum`, `table`, `then`, `to`, `trailing`, `trigger`, `union`, `unique`, `using`, `values`, `when`, `where`, `with`
Also notice that column names will be lowered case.
### Column types
Before saving the data source (or when editing it), you are able to amend the column data types. You will find a
setting icon below the column name and, when clicking on it, you will be able to select the correct type for the column,
as shown in the following figure.
The default data type is `STRING`, however you can pick any of the following types:
| Data source type |
|-----------------------------|
| `BOOLEAN` |
| `DECIMAL` |
| `INTEGER` |
| `STRING` |
| `DATE` |
| `TIME` (time zoned) |
| `TIME` (not time zoned) |
| `DATETIME` (time zoned) |
| `DATETIME` (not time zoned) |
Example
| username (STRING) | age (INTEGER) | first_name (STRING) | height (DECIMAL) | email (STRING) | dob (DATETIME, time zoned) | premium (BOOLEAN) |
|-------------------|---------------|---------------------|------------------|------------------|-----------------------------------------|-------------------|
| admin | 64 | Bob | 1.8 | bob@example.com | 1962-12-31T16:50:31+05:00 | true |
| bill | 27 | Bill | 1.92 | bill@example.com | 1997-05-24T19:18:12Z | false |
| jill | 15 | Jill | 1.70 | jill@example.com | 2009-11-07T04:34:01+01:00[Europe/Paris] | false |
| jane | 74 | Jane | 1.81 | jane@example.com | 1952-01-13T10:10:10-12:00 | true |
#### Date type
For `DATE`, `TIME` and `DATETIME` types, you can specify your own format string using the elements in the following table:
|Letter|Date or Time Component|Presentation|Examples|
|--- |--- |--- |--- |
|G|Era designator|Text|AD|
|y|Year|Year|1996; 96|
|Y|Week year|Year|2009; 09|
|M|Month in year|Month|July; Jul; 07|
|w|Week in year|Number|27|
|W|Week in month|Number|2|
|D|Day in year|Number|189|
|d|Day in month|Number|10|
|F|Day of week in month|Number|2|
|E|Day name in week|Text|Tuesday; Tue|
|u|Day number of week (1 = Monday, ..., 7 = Sunday)|Number|1|
|a|Am/pm marker|Text|PM|
|H|Hour in day (0-23)|Number|0|
|k|Hour in day (1-24)|Number|24|
|K|Hour in am/pm (0-11)|Number|0|
|h|Hour in am/pm (1-12)|Number|12|
|m|Minute in hour|Number|30|
|s|Second in minute|Number|55|
|S|Millisecond|Number|978|
|z|Time zone|General time zone|Pacific Standard Time; PST; GMT-08:00|
|Z|Time zone|RFC 822 time zone|-0800|
|X|Time zone|ISO 8601 time zone|-08; -0800; -08:00|
### Creating & Editing Database Data Sources
Source: https://docs.wiremock.io/data-sources/managing-database-data-sources
- Click on the button, `+Create new data source`.
- Choose `Database based` from the dropdown
- Provide a name for your data source.
- Select the database connection you wish to use with this data source
- Enter the name of the table you wish to use with this data source. This can be the name of a table, or a view within
your database.
- Click `save` at the bottom of the page.
Once the data source has been saved you can view a preview (the first 10 rows) of the data returned from the specified
table by navigating to the data sources page and clicking on the data source you wish to preview.
If the specified table could not be found, an error will be displayed.
## Editing a database data source
Data sources can be updated after creation.
To edit a data source:
- Navigate to the Data Sources page.
- Click on the data source you wish to edit, from the list provided.
- Update your data source.
- Click on the `save` at the bottom of the page.
Once in the data source page, you will be able to:
- Change the name of the data source
- Change the database connection used by the data source
- Change the table name referenced by the data source
### Deleting Data Sources
Source: https://docs.wiremock.io/data-sources/deleting-data-sources
## Deleting a Data Source
Data sources can be deleted from your organisation. To delete a data source:
- Navigate to the [Data sources page](https://app.wiremock.io/data-sources).
- Click on the delete icon for the data source you want to remove.


![]()

- Click on the link, `View Connections`
- Click on the button, `Create new database connection`
- Fill out the form with the details of your database connection
The connection details you will need are:
* A name for the connection. This must be unique across all the database connections in you organisation
* A database type - we currently support `Postgresql`, `MySql`, `Oracle` and `MS SQL Server`
* The hostname for the connection
* The port the database is running on
* The name of the database
* The username used to connect to the database
* The password used to connect to the database
Once you have entered all the details for your database connection you can test that they allow a successful connection
to your database by clicking on the `Test connection` button.
If the connection request is unsuccessful, an error message will be displayed.
- Once you are happy with your database connection details, click on the `Save` button to save your connection details.
For security, the password is not returned on the edit screen. You can still update any of the fields and if you
leave the password field blank it will keep the existing password and update all other fields. To update your
password or re-test the connection you will need to enter your password in the field provided.
## Deleting a database connection
Database connections can be deleted from your organisation. To delete a database connection, you must be an
administrator of your organisation.
To delete a database connection:
- Navigate to the [Database connections page](https://app.dev.wiremock.cloud/data-sources/connections).
- Click on the delete icon for the connection you want to remove.



Once you have selected the desired subject and picked the appropriate role for that subject, click the "Invite"/ "Share" button.
The subject(s) should not be able to view the data source from their WireMock Cloud account.
### Data Sources - Plan Limits
Source: https://docs.wiremock.io/data-sources/plan-limits
WireMock Cloud applies limits to data sources dependent upon the plan your organisation is subscribed to.
On the WireMock Cloud free plan, an account is limited to a maximum of 3 data sources.
Each data source can contain up to 100 rows and each row must not exceed 10KB in size.
During the enterprise trial period, this limit is increased to 1000 rows with a maximum row size of 100KB.
To increase the limits applied to your organisation, [contact the WireMock team today](https://www.wiremock.io/contact-now).
## Disabled data sources
If an account/organisation is downgraded to a plan that causes their data sources to exceed the new plan's limits, these exceeding data sources will be disabled.
Any stubs with disabled data sources attached will lose their [data matching abilities](#stub-matching) and [access to the data](#data-source-response-templating) in their response template.
Disabled data sources can be enabled at any time by updating them to fit within the account plan's limits or, of course, by [upgrading to a different plan](https://www.wiremock.io/contact-now).
### Stub Matching
If a stub is using a data source that has been disabled, the stub will no longer [match incoming requests](./overview#custom-stub-matching) if the
`Matches stub only if data is found` tick box is checked on the Stub form. If this tick box is not checked, the stub
will continue to match incoming requests, but the data source will not be queried.
### Data source response templating
If a data source is disabled, any [response templates](./overview#rendering-data-in-response) that are using the data source will no longer be able to access the
data source data. The response template will still be rendered, but the data source data will not be available.
### OpenAPI Mocking and Prototyping
Source: https://docs.wiremock.io/openAPI/openapi
WireMock Cloud supports an OpenAPI mock API type that provides both incremental generation of stubs from OpenAPI and OpenAPI generation from stubs. Mock APIs of this type also have an associated auto-generated set of public documentation pages.
This supports two types of workflow:
1. Automatic generation/amendment of a mock API from an existing OpenAPI doc as it evolves,
2. API prototyping - defining API behaviour via stubs and auto-generating OpenAPI + documentation.
These workflows can be combined i.e. when prototyping new behaviour for an existing API.
## Getting started
From the app's home screen, create a new mock API and choose the OpenAPI type:
When the new mock API is created an extra item will be present on the left-hand nav bar, taking you to the OpenAPI editor page:
Navigating to the Settings tab on the same page, toggling on "Enable public API documentation" and clicking the link underneath will show the public API documentation (which will be initially empty apart from header information since there are no paths defined in the OpenAPI doc).
## Generating stubs from OpenAPI
Stubs will be created or updated whenever changes are saved to the OpenAPI doc.
Add a new path entry and click Save:
Then navigate to the Stubs page and see that two new stubs have been created - one with specific request parameters required and one "default" i.e. will match regardless of specific parameter values provided the method and URL path are correct.
Stubs will be generated following the [stub generation rules](#stub-generation-rules).
### Updating an OpenAPI doc
When an OpenAPI doc is updated, for every `path-method-status-contentType`, existing stubs will be updated if any of the following apply:
- The existing stub was generated from an example and the example hasn't changed its name.
- If there is one example within the given `path-method-status-contentType` which shares the response body with the existing stub.
- If the `path-method-status-contentType` only provides a single example.
- If the `path-method-status-contentType` doesn't provide examples at all.
If none of the conditions above are satisfied, one or more stubs will be generated following the [stub generation rules](#stub-generation-rules).
WireMock Cloud takes a non-destructive approach to your stubs. This means that if you delete a path, method, status
or contentType, the stub that represents that OpenAPI element will remain in your Mock API. This also applies to updating
elements in your OpenAPI. For example, if you update a path in your OpenAPI from `/orders` to `/v1/orders` the path
will be classed as a new path and a new stub will be created. The old stub will not be deleted.
If you are modeling new data scenarios and you add new stubs to your Mock API after generating stubs from an OpenAPI
specification, these stubs will not always be updated when you update your OpenAPI specification. If those new stubs
do not match an example in your OpenAPI specification, they will not be updated when you update your OpenAPI specification
(adding a new parameter for example) and you will need to update those manually.
### Stub generation rules
When updating an OpenAPI doc, the resulting stubs from new OpenAPI elements will be added.
Stub generation will be based on the following rules:
* `304` response:
- Request header matcher `If-None-Match` with specific value `12345`.
* `422` response:
- Only one stub will be generated, with a request body matcher not matching the schema or missing.
- If more than one response example provided, it will pick one randomly as the response body.
- If no response example provided, the response body will be autogenerated based on the schema.
* `400` response:
- Only one stub will be generated, with neither request parameters nor body present or matching the schema.
- If more than one response example provided, it will pick one randomly as the response body.
- If no response example provided, the response body will be autogenerated based on the schema.
* Any other response status:
- If no example is provided, it will generate a stub with autogenerated request parameters and response, based on schema.
- If at least one example is provided:
- It will generate one stub per example, using specific request parameter matchers and taking the example as the response body.
- The request parameter matchers will be autogenerated based on the schema, unless the extension `x-parameter-values` is provided (as explained [here](./swagger)), in which case it will be used to generate the expected values of the parameter matchers.
### Controlling generated parameter values in your stubs
If an OpenAPI element has a parameter (header for example) that is set to `required: true` then the stub will be generated
or updated with that parameter. WireMock Cloud adds a value for that parameter to match on. You can control the value
generated in your stubs using various OpenAPI elements:
If no min or max length are provided in the schema, defaults of a minimum of 3 and a maximum of
200 is used. Therefore, an OpenAPI specification snippet like the following:
```yaml
paths:
/trips/{tripId}:
delete:
summary: Cancel a booked trip
parameters:
- name: tripId
in: path
required: true
```
Could generate a `tripId` equalsTo matcher with the following value - `gtpq1fggnuolb31tya6rrc1tye1am5bkzw5kjxxeyscx9lb3zhla`
Adding a `minLength` and a `maxLength` to the schema will control the size of the random string. The snippet below:
```yaml
paths:
/trips/{tripId}:
delete:
summary: Cancel a booked trip
parameters:
- name: tripId
in: path
required: true
schema:
type: string
maxLength: 5
minLength: 2
```
Could generate a `tripId` equalsTo matcher with the following value - `aspp`
You can force a value to be used in the matcher by creating an enum with only one value. This is effectively the same as
generating a constant:
```yaml
paths:
/trips/{tripId}:
delete:
summary: Cancel a booked trip
parameters:
- name: tripId
in: path
required: true
schema:
type: string
enum:
- "1"
```
If an enum is used with multiple values, then a random item from the enum is used in the matcher.
Alternatively, a regex pattern can be used in the schema to further control the value used in the matcher:
```yaml
paths:
/trips/{tripId}:
delete:
summary: Cancel a booked trip
parameters:
- name: tripId
in: path
required: true
schema:
type: string
pattern: "^trip-id-\\d{8}$"
```
Could generate a `tripId` equalsTo matcher with the following value - `trip-id-68975013`.
Optional `minLength` and `maxLength` elements can be used to further control the generated value:
```yaml
paths:
/trips/{tripId}:
delete:
summary: Cancel a booked trip
parameters:
- name: tripId
in: path
required: true
schema:
type: string
pattern: "^trip-id-\\d{8}$"
maxLength: 9
minLength: 2
```
Could generate a `tripId` equalsTo matcher with the following value - `trip-id-6`.
#### Default stubs
[//]: # (WARNING: This heading is referenced by the UI. Do not change it without changing the link in the UI.)
Optionally, for each path and method in the OpenAPI specification with a response status of 2xx, a "default" stub can also be generated.
This default stub will not contain any specific request parameter matchers, only a request body matcher that matches the request body schema in the OpenAPI specification, if a schema is provided.
To turn on/off the generation of default stubs, go to the Settings tab of the OpenAPI page, where the toggle is located.
## Prototyping - generating OpenAPI from stubs
OpenAPI elements will be generated or updated when stubs are created or changed.
Try creating a stub with a new path template that doesn't yet exist in the OpenAPI document:
On save, the path plus operation, responses, schemas and examples will be added to the OpenAPI spec and also to the public documentation.
Automatic generation of OpenAPI to stubs and vice versa can be turned off in the Settings tab of the OpenAPI page.
### Import & Export - Swagger and OpenAPI
Source: https://docs.wiremock.io/openAPI/swagger
Swagger / OpenAPI is undoubtedly the most widely used description language for REST and REST-like APIs. WireMock Cloud supports automatic generation of mock APIs from imported Swagger and OpenAPI specifications.
See [Import and Export Overview](/import-export/overview) for basic importing instructions via the UI and [Importing and Export via the API](../import-export/api) for directions on automating
imports via WireMock Cloud's API.
## Customising the import
When importing from a Swagger/OpenAPI spec, it's often useful to be able to control
how certain aspects of the generated stubs are produced. WireMock Cloud supports a number
of extension attributes that can be added to your spec document for this purpose.
### Specifying URL path and query parameters
When WireMock Cloud converts a response example to a stub, by default it will generate random values for URL path and query parameters.
However, if a response uses the multiple example format, you can specify the exact parameter values you wish to be required
by the stub. This can be useful if your test cases or application under test expects specific
responses to be available in your mock API.
For instance, given the following Open API path element:
```yaml
/people/{id}:
description: People by ID
parameters:
- name: id
in: path
required: true
schema:
type: string
get:
description: Get a person
parameters:
- name: fields
in: query
required: true
schema:
type: string
enum:
- full
- summary
responses:
'200':
description: People search returned successfully
content:
application/json:
examples:
one:
summary: First example
x-parameter-values:
id: abc123
fields: summary
value: |
{ "name": "John" }
two:
summary: Second example
x-parameter-values:
id: cba321
fields: full
value: |
{ "name": "Jeff", id: "cba123" }
```
Two stubs will be created from the above example.
One will have a URL path equal to `/people/abc123` and a required query parameter of `fields=summary`.
The other will have a URL path equal to `/people/cba321` and a required query parameter of `fields=full`.
Any values not specified in this manner will be randomly generated based on the parameter's schema.
### Controlling data generation from schemas
When importing a response with a schema but no examples, WireMock Cloud will randomly generate an example
that conforms to the schema.
For each schema attribute an attempt will be made to determine the data type, using the
`format` if present, but if not making a guess based on the field name. For instance,
a `string` attribute named `date_of_birth` will result in the generation of an ISO8601 local
date within the past 99 years e.g. `1971-08-02`.
However, you can override this behaviour and specify which data generation strategy should be used.
WireMock Cloud uses [Faker](https://github.com/DiUS/java-faker) to generate example data, and
you can specify the specific faker to use by adding an `x-faker` attribute to your schema element e.g.
```yaml
schema:
type: string
x-faker: name.first_name
```
This can be used both in parameter declarations and response body schemas.
All of the fakers [listed here](https://github.com/DiUS/java-faker/tree/master/src/main/resources/en)
can be used, plus there are some additional rules supplied by WireMock Cloud. The following lists all of the most commonly used, plus all supplied by WireMock Cloud:
* `name.name`
* `name.first_name`
* `name.last_name`
* `name.name_with_middle`
* `name.title`
* `name.prefix`
* `name.suffix`
* `name.username`
* `id.alphanumeric_id`
* `id.uuid`
* `date_and_time.birthday`
* `date_and_time.past_date_time`
* `date_and_time.future_date_time`
* `uri.url`
* `lorem.word`
* `lorem.sentence`
* `lorem.paragraph`
* `currency.code`
* `address.street_address`
* `address.secondary_address`
* `address.city_name`
* `address.state`
* `address.postcode`
* `country.name`
* `country.code2`
* `country.code3`
* `phone_number.phone_number`
* `avatar.image`
The SSH public key for the key you selected will be displayed at the bottom of the configuration.
[Add this key to your Git repository.](#adding-ssh-keys-to-your-git-repository)
When you navigate to the Document tab of the OpenAPI page, there will be buttons for performing Git operations on your
OpenAPI document.
Clicking the Pull button will retrieve the contents of the file at the configured path in your Git repository and save
it in WireMock Cloud.
The document will be validated and stubs generated like normal.
The pulled document will appear in the document text area.
Note, this will not immediately overwrite any local changes you have made to the specification (see
[Git conflicts](#handling-git-conflicts) for details).
Clicking the Push button in the Document tab of the OpenAPI page will push your currently saved OpenAPI document on
WireMock Cloud to the configured Git repository.
If the file does not exist on the configured branch of the Git repository, then it will be created by this action.
If you wish to push to your Git repository, ensure that write access is granted to the SSH key when you add it to your
repository, if required by the platform (e.g. GitHub).
With the Git integration enabled, changes can still be saved to WireMock Cloud's copy of the OpenAPI document
independently of the configured Git repository.
WireMock Cloud and your Git repository are only synchronized when the document is pulled or pushed.
## Handling Git Conflicts
[//]: # (WARNING: This heading is referenced by the UI. Do not change it without changing the link in the UI.)
There are circumstances where performing a pull or push will cause conflicts with your mock API's copy of your OpenAPI
specification.
This can occur when a pull is attempted after changes have been applied to your mock API's copy of the specification
that have yet to be pushed to your repository, or when pushing after changes have been made to the file in the
repository since the last time it was pulled into WireMock.
In these cases, attempting a pull or push will display a dialog explaining that your mock API is out of sync with the
repository and ask if you wish to overwrite the document on WireMock (when pulling) or the document in the repository
(when pushing).
If this dialog is cancelled, no changes will occur in WireMock or your repository.
If you are receiving these conflict messages and are unsure of what action to perform, WireMock recommends performing
an overwriting push to the repository, rather than an overwriting pull to your mock API, and resolving any issues using
external Git tooling.
This ensures that no data is lost, since all changes will be logged in version control.
## Testing Connections to Your Git Repository
If you want to test that your Git configuration is correct before attempting a pull or push (or even saving the
configuration), you can use the "Test Connection" button on the settings page.
Simply fill in the configuration fields and press the button.
If WireMock Cloud is able to connect to your Git repository, then a success will be displayed.
Otherwise, a message will be displayed explaining what went wrong.
## Adding SSH Keys to Your Git Repository
[//]: # (WARNING: This heading is referenced by the UI. Do not change it without changing the link in the UI.)
In order for WireMock Cloud to be able to communicate with your Git repository, you must add the SSH public key displayed in your mock API's OpenAPI settings to the repository.
The process for adding the public key to your Git repository depends on the method you are using to host your Git
repository.
Below are instructions for adding keys to your repository on popular hosting platforms.
These instructions are up-to-date as of writing, but are subject to changes outside WireMock's control.
### GitHub
If you are hosting a repository on [GitHub](https://github.com), you can add the key to your repository via the "Deploy
keys" page of the repository settings tab.
Make sure to allow the key write access if you want to push to the repository from WireMock Cloud.
### Bitbucket
If you are hosting a repository on [Bitbucket](https://bitbucket.org), you can add the key to your repository via the
repository's "Access keys" page.
Bitbucket's access keys are limited to read-only access to a repository.
This means pushing from WireMock Cloud is not possible when using access keys.
If write access is required, the key can be added to a user's personal SSH keys.
This will allow the key write access to all repositories that the user has access to.
Therefore, it may be advisable to create a specific user for WireMock Cloud in your Bitbucket organisation that only has
access to the desired repository.
### Gitlab
If you are hosting a repository on [Gitlab](https://gitlab.com), you can add the key to your repository via the
repository's "Deploy keys" section of the repository settings page.
Make sure to grant the key write permissions if you want to push to the repository from WireMock Cloud.
### Self-Hosted Server
If you are hosting a repository on a server that you maintain, adding the key to your repository will generally involve
adding it to the Git user's `.ssh/authorized_keys` file.
For example, if your Git repository address is `git-user@my-git-server.com:path/to/repository.git`, you will likely have
to append the key to the contents of `/home/git-user/.ssh/authorized_keys` on the server that `my-git-server.com`
addresses.
Approaches may vary, so it is best to consult your system administrator.
For security purposes, WireMock recommends creating a specific user for WireMock Cloud on your server with read
permission on the Git repository directory only (and write permission if pushing from WireMock Cloud is desired).
### OpenAPI Validation
Source: https://docs.wiremock.io/openAPI/openapi-validation
Validation settings can be used to ensure that requests made to your mock API and responses returned by your mock API
are compliant with your OpenAPI specification.
Settings for OpenAPI validation can be found in the Settings tab on the OpenAPI page.
There are four options for OpenAPI validation: no validation, soft validation (the default), hard validation, and hard
(spec-compliant) validation.
The "no validation" option will have no effect on your mock API.
Enabling soft validation will cause non-compliant requests to contain validation warnings in your mock API's request log.
Any request to the mock API and/or any response returned by the mock API containing data/attributes that do not conform
to the mock API's OpenAPI document will be highlighted on the request log page.
Details of how the request was invalid can also be viewed in the request log.
Enabling hard validation will cause the same request log behavior as soft validation, with the added functionality of
returning error responses containing details of validation issues to invalid requests.
## Hard (spec-compliant) validation
Hard (spec-compliant) validation builds on hard validation by returning error responses whose body and `Content-Type`
are taken directly from your OpenAPI specification, rather than a fixed generic format.
When a request fails validation, WireMock Cloud looks up the error response declared in your spec for the relevant
status code (typically `400` or `422` for request failures, `500` for response failures).
[`4XX`, `5XX` and `default` response definitions](https://spec.openapis.org/oas/v3.2.0.html#fixed-fields-13) are
respected.
The response body example defined for that status code is rendered as a
[response template](/response-templating/basics), with the following variables available:
| Variable | Description |
|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
| `{{message}}` | A human-readable summary of the validation failure, e.g. `Request failed OpenAPI validation` |
| `{{errors}}` | A list of individual validation error message strings, e.g. `"required property 'field' not found"`. Iterate with `{{#each errors}}{{this}}{{/each}}`. |
| `{{response.status}}` | The HTTP status code of the error response |
All standard WireMock response template helpers (e.g. `{{request.method}}`, `{{request.path}}`) are also available.
If the matched error response has a schema but no example, WireMock Cloud generates a body from the schema.
If no matching error response is defined at all, or the template fails to render, WireMock Cloud falls back to the
same [generic error body](#error-response-body) used by hard validation.
### Content negotiation
When the error response in your spec declares multiple media types, WireMock Cloud negotiates the response
`Content-Type` from the client's `Accept` header, serving the matching body. If no `Accept` header is present,
the first declared concrete media type is used.
## Error response body
In hard validation mode, an invalid request receives a JSON error response in WireMock Cloud's
standard error format. The same body is returned in hard (spec-compliant) mode whenever a
spec-compliant body cannot be produced — that is, when the specification declares no matching error
response, or its template fails to render.
The response body matches the following schema:
```yaml
$schema: https://json-schema.org/draft/2020-12/schema
type: object
required: [errors]
properties:
errors:
type: array
description: One entry per validation failure
items:
type: object
required: [code, title, detail]
properties:
code:
const: 103
description: WireMock Cloud error code for OpenAPI validation errors
title:
const: OpenAPI schema validation error
description: Error category
detail:
type: string
description: The individual validation error message
examples:
- errors:
- code: 103
title: OpenAPI schema validation error
detail: "required property 'field' not found"
```
## Validation sub-events
Whenever validation is enabled — soft, hard, or hard (spec-compliant) — each request or response that
fails validation is recorded against the served request in the request log as an `OpenAPI` sub-event
carrying the structured failure details. In soft mode this is the only effect; the hard modes
additionally return an error response.
Each sub-event has the following form, where `timeOffsetNanos` is the time of the failure relative to
the start of request handling:
```json
{
"type": "OpenAPI",
"timeOffsetNanos": 0,
"data": { }
}
```
The `data` object matches the following schema:
```yaml
$schema: https://json-schema.org/draft/2020-12/schema
$defs:
BaseValidationError:
type: object
required: [message, schemaPaths]
properties:
message:
type: string
description: Human-readable error message
schemaPaths:
type: array
description: Locations in the OpenAPI spec schema that triggered the error
items:
type: object
required: [path]
properties:
path:
type: string
description: JSON pointer path in the OpenAPI spec schema
start:
type: object
properties:
lineNumber: { type: integer }
columnNumber: { type: integer }
end:
type: object
properties:
lineNumber: { type: integer }
columnNumber: { type: integer }
# A simple validation error carries only the base fields; unevaluatedProperties
# forbids the schema-error fields, so a partial schema error matches neither
# branch of the oneOf below and is rejected.
SimpleValidationError:
allOf:
- $ref: '#/$defs/BaseValidationError'
unevaluatedProperties: false
SchemaValidationError:
allOf:
- $ref: '#/$defs/BaseValidationError'
- required: [type, within, path, arguments]
properties:
type:
type: string
description: Validation rule that failed, e.g. required, type, minimum
within:
type: string
enum: [body, query, header, path, cookie]
description: Part of the HTTP message that was invalid
path:
type: string
description: JSON path to the invalid value within the payload
arguments:
type: array
items:
type: [string, number, boolean]
description: Values relevant to the failing rule, e.g. expected type or missing property name
details:
type: object
description: Additional rule-specific detail
type: object
required: [httpMessage, errors]
properties:
httpMessage:
type: string
enum: [request, response]
description: Whether the request or response failed validation
errors:
type: array
items:
oneOf:
- $ref: '#/$defs/SchemaValidationError'
- $ref: '#/$defs/SimpleValidationError'
examples:
- httpMessage: request
errors:
- message: "required property 'field' not found"
type: required
within: body
path: "$"
arguments: [field]
details:
property: field
schemaPaths:
- path: "#/paths/~1posts~1{id}/put/requestBody/content/application~1json/schema/required"
start: { lineNumber: 16, columnNumber: 14 }
end: { lineNumber: 17, columnNumber: 14 }
```
### Import & Export - Overview
Source: https://docs.wiremock.io/import-export/overview
You can import your [Mountebank stubs](../import-export/mountebank), [Har log](../import-export/har),
[Swagger](/openAPI/swagger/) and [OpenAPI](/openAPI/swagger/) specifications and [Postman](../import-export/postman)
collections into WireMock Cloud in order to auto-generate stubs in your mock API. Swagger 2.x and OpenAPI 3.x are supported,
in both JSON and YAML format.
You can also import and export stubs in [WireMock](../import-export/wiremock/) JSON format. This can be used to move projects between WireMock and WireMock Cloud, store your mock APIs in source control and make copies of WireMock Cloud APIs.
## Importing - basics
To import from any of the supported formats, navigate to the Stubs page of the
mock API you'd like to import into, then click the Import button.
Then either paste the content to be imported:
Or upload it as a file:
The WireMock JSON format is also WireMock Cloud's native format, so when a file of this type is imported,
the stubs created correspond exactly to the file contents.
However, when importing from Swagger and OpenAPI, stubs are generated according to
a set of conversion rules. These can be [tweaked and customised in a number of ways](/openAPI/swagger#customising-the-import).
You can also automate imports via [WireMock Cloud's API](../import-export/api).
## Exporting
To export the current mock API's stubs in WireMock Cloud/WireMock JSON format, click the Export button:
Then click the download link:
### Import & Export - WireMock
Source: https://docs.wiremock.io/import-export/wiremock
WireMock Cloud and [WireMock OSS](https://wiremock.org/) share the same native JSON format for stubs, so mock APIs
can be imported and exported between the two.
JSON exports can also be stored in source control, and used to clone or move stubs
between WireMock Cloud APIs.
## Importing a mock API into WireMock Cloud from WireMock
Assuming you're running a WireMock instance on port 8080, you can export all the
stubs currently defined via the admin API:
Then call the WireMock import API with the file you downloaded:
Postman is one of the most widely used tools for testing HTTP services, and its
collection format has become a de-facto standard for representing request and response examples.
WireMock Cloud can import your Postman collection and convert it into a collection of stubs.
Postman files are imported in exactly the same way as other formats.
See [Import and Export Overview](./) for basic importing instructions via the UI and
[Importing and Export via the API](./api) for directions on automating
imports via WireMock Cloud's API.
### Import & Export - Via the API
Source: https://docs.wiremock.io/import-export/api
A mock API's stubs can be exported in bulk via the admin API. This can be useful for backing
up your API to source control, or cloning the contents of one API into another.
## Importing
To import any of the supported formats (Swagger, OpenAPI, WireMock Cloud WireMock JSON),
execute a `POST` request to the stub import URL e.g.:
Shortcuts are not triggered while you are typing in a text field.
## Global
These shortcuts are available everywhere in the app:
| Shortcut | Action |
| ----------- | ------------------------------------ |
| `Shift + m` | Go to Mock APIs |
| `Shift + d` | Go to Data sources |
| `Shift + a` | Open the AI Assistant |
| `Shift + ?` | Toggle the keyboard shortcuts dialog |
You would need to send in the request body for the stub to match exactly that JSON
in order for the stub to be matched:
This will allow requests like the following to succeed:
This would permit the following to match:
This would permit the the following to match:
The following JSON will be matched:
If you do this, the JSON input will be considered a match if the expression returns
1 or more elements.
This feature is primarily present for compatibility with WireMock projects, and
generally it is better to use sub-matches as this results in simpler JSONPath
expressions and more useful debug output when there is a non-match.
### Common JSONPath examples
Matching on a specific array element by position.
`$.sizes[1]` `equal to` `M`
would match:
```json
{
"sizes": ["S", "M", "L"]
}
```
Matching on an element of an object found via another element.
`$.addresses[?(@.type == 'business')].postcode` `contains` `N11NN`
would match:
```json
{
"addresses": [
{
"type": "home",
"postcode": "Z55ZZ"
},
{
"type": "business",
"postcode": "N11NN"
}
]
}
```
It is necessary to use `contains` in this instance as a JSONPath expression containing
a query part (between the `[?` and `]`) will always return a collection
of results.
Matching an element found recursively.
`$..postcode` `contains` `N11NN`
would match:
```json
{
"addresses": [
{
"type": "home",
"postcode": "Z55ZZ"
},
{
"type": "business",
"postcode": "N11NN"
}
]
}
```
and would also match:
```json
{
"address": {
"type": "business",
"postcode": "N11NN"
}
}
```
### Request Matching - Matching URLs
Source: https://docs.wiremock.io/request-matching/url
For most HTTP APIs the URL is the primary means by which the appropriate action
is selected. WireMock Cloud provides a number of different options for matching the
URL of an incoming request to a stub.
## Path vs path + query
It's important to be clear exactly which part(s) of the URL you wish to match.
The default strategy WireMock Cloud uses is to match both the path and query parts of the
URL. For instance, if you were you to enter the following in a stub's URL field:
```
/my/path?q=abc&limit=10
```
then the stub would only be matched if that exact path and query were present e.g.
for the URL:
```
https://my-api.wiremockapi.cloud/my/path?q=abc&limit=10
```
However, it's often desirable just to look at the path part of the URL, and either
ignore the query completely or specify it more flexibly using dedicated query parameter
matchers (see [Query Parameters](/advanced-stubbing/#advanced-request-parameter-matching)).
Dedicated query matchers can be useful if the parameter order in the URL can change,
or if you need to match more loosely on the value e.g. using `contains` rater than
exact equality.
To do this, you need to change the URL match type in the Advanced section to `Path`
and ensure you only specify a path in the URL field e.g.
```
/my/path
```
This would now match any of the following URLs:
```
https://my-api.wiremockapi.cloud/my/path?q=abc
https://my-api.wiremockapi.cloud/my/path?q=abc&limit=10
https://my-api.wiremockapi.cloud/my/path
https://my-api.wiremockapi.cloud/my/path?randomqueryparam=123
```
## Match type - exact vs. regular expression
In addition to choosing the URL part(s) you wish to match, you can also choose whether
to check for exact equality or a regular expression match. By default WireMock Cloud uses
an equality check, but this can be changed in the Advanced section.
Choosing the `Path regex` match type can be particularly useful in cases where
the API you're mocking uses path parameters and you wish to provide a meaningful response
to a specific URL pattern regardless of the specific parameter values.
For instance, choosing `Path regex` as the match type with the following URL
```
/users/[0-9]+
```
would match any of the following request URLs:
```
/users/1
/users/9832749823
/users/321
```
A powerful approach is to combine this with [Response Templating](/response-templating/basics/)
so that the ID used in the URL can be inserted into the response body.
You can also now reference the value of a request's path variables by name in the response template.
## Matching any URL
In some cases you need a stub to match any request URL. A common use case for this
is providing a low priority default response which is matched only if nothing else does.
You might also choose to proxy the request to another endpoint in this case.
For this purpose use the `Any URL` option from the URL match type list under Advanced.
### Request Matching - Matching XML bodies
Source: https://docs.wiremock.io/request-matching/xml
When stubbing API functions that accept XML request bodies we may want to
return different responses based on the XML sent. WireMock Cloud provides two match types
to supports this case - `equalToXml` and `matchesXPath`, which are described
in detail in this article.
## Matching via XML equality - `equalToXml`
The `equalToXml` match operator performs a semantic comparison of the input XML
against the expected XML. This has a number of advantages over a straight string
comparison:
* Ignores differences in whitespace
* Ignores element and attribute order
* Supports placeholders so that specific elements or attributes can be excluded from the comparison
By default `equalToXml` will match the input to the expected XML if all elements
and attributes are present, have the same value and there are no additional
elements or attributes.
For instance, given the following configuration:
The following XML would match:
```xml
The following XML will match:
```xml
The following XML will match:
```xml
When you request the stub, the `random` helper will populate those fields with random values based on the key provided.
The above example will generate something that looks similar to the following output:
```json
{
"id": "b37f9d89c35a6a9d17f5555ffb5bd4646cdb096cd4bf2529dbc00a98b6d0be64",
"username": "jarvis.gorczany",
"name": "Dr. Magda Rohan",
"email": "karol.orn@example.com",
"ssn": "861-67-1370",
"company": "Sanford LLC",
"role": "Supervisor",
"status": "Idle",
"last_ip": "132.29.169.80",
"address": "737 Burma Meadows, North Dolly, IA 37183",
"phone": {
"home": "+1 815-419-9640",
"work": "(502) 606-4468 x3739",
"mobile": "518-317-6223"
},
"avatar": "https://robohash.org/lcgrxnvh.png",
"spirit_animal": "manatee",
"favorite_color": "sky blue"
}
```
Every time you request the stub, the `random` helper will generate new random values for the fields based on the key.
## Reference
The following keys are supported for use with the `random` helper:
### Category - Base
#### Key - Address
```handlebars
{{ random 'Address.state' }}
{{ random 'Address.country' }}
{{ random 'Address.streetName' }}
{{ random 'Address.zipCode' }}
{{ random 'Address.postcode' }}
{{ random 'Address.stateAbbr' }}
{{ random 'Address.citySuffix' }}
{{ random 'Address.cityPrefix' }}
{{ random 'Address.city' }}
{{ random 'Address.cityName' }}
{{ random 'Address.latitude' }}
{{ random 'Address.longitude' }}
{{ random 'Address.latLon' }}
{{ random 'Address.lonLat' }}
{{ random 'Address.timeZone' }}
{{ random 'Address.mailBox' }}
{{ random 'Address.streetAddressNumber' }}
{{ random 'Address.streetAddress' }}
{{ random 'Address.secondaryAddress' }}
{{ random 'Address.zipCodePlus4' }}
{{ random 'Address.streetSuffix' }}
{{ random 'Address.streetPrefix' }}
{{ random 'Address.countryCode' }}
{{ random 'Address.buildingNumber' }}
{{ random 'Address.fullAddress' }}
```
#### Key - Ancient
```handlebars
{{ random 'Ancient.god' }}
{{ random 'Ancient.primordial' }}
{{ random 'Ancient.titan' }}
{{ random 'Ancient.hero' }}
```
#### Key - Animal
```handlebars
{{ random 'Animal.name' }}
{{ random 'Animal.species' }}
{{ random 'Animal.genus' }}
{{ random 'Animal.scientificName' }}
```
#### Key - App
```handlebars
{{ random 'App.name' }}
{{ random 'App.version' }}
{{ random 'App.author' }}
```
#### Key - Appliance
```handlebars
{{ random 'Appliance.brand' }}
{{ random 'Appliance.equipment' }}
```
#### Key - Artist
```handlebars
{{ random 'Artist.name' }}
```
#### Key - Australia
```handlebars
{{ random 'Australia.locations' }}
{{ random 'Australia.animals' }}
{{ random 'Australia.states' }}
```
#### Key - Aviation
```handlebars
{{ random 'Aviation.aircraft' }}
{{ random 'Aviation.airport' }}
{{ random 'Aviation.METAR' }}
{{ random 'Aviation.flight' }}
{{ random 'Aviation.airline' }}
```
#### Key - Aws
```handlebars
{{ random 'Aws.region' }}
{{ random 'Aws.accountId' }}
{{ random 'Aws.acmARN' }}
{{ random 'Aws.albARN' }}
{{ random 'Aws.subnetId' }}
{{ random 'Aws.vpcId' }}
{{ random 'Aws.albTargetGroupARN' }}
{{ random 'Aws.route53ZoneId' }}
{{ random 'Aws.securityGroupId' }}
```
#### Key - Azure
```handlebars
{{ random 'Azure.region' }}
{{ random 'Azure.tenantId' }}
{{ random 'Azure.firewall' }}
{{ random 'Azure.virtualWan' }}
{{ random 'Azure.serviceBus' }}
{{ random 'Azure.keyVault' }}
{{ random 'Azure.subscriptionId' }}
{{ random 'Azure.resourceGroup' }}
{{ random 'Azure.managementGroup' }}
{{ random 'Azure.applicationGateway' }}
{{ random 'Azure.bastionHost' }}
{{ random 'Azure.loadBalancer' }}
{{ random 'Azure.networkSecurityGroup' }}
{{ random 'Azure.virtualNetwork' }}
{{ random 'Azure.appServiceEnvironment' }}
{{ random 'Azure.appServicePlan' }}
{{ random 'Azure.loadTesting' }}
{{ random 'Azure.staticWebApp' }}
{{ random 'Azure.virtualMachine' }}
{{ random 'Azure.storageAccount' }}
{{ random 'Azure.containerRegistry' }}
{{ random 'Azure.containerApps' }}
{{ random 'Azure.containerAppsEnvironment' }}
{{ random 'Azure.containerInstance' }}
{{ random 'Azure.cosmosDBDatabase' }}
{{ random 'Azure.sqlDatabase' }}
{{ random 'Azure.mysqlDatabase' }}
{{ random 'Azure.postgreSQLDatabase' }}
{{ random 'Azure.serviceBusQueue' }}
{{ random 'Azure.serviceBusTopic' }}
{{ random 'Azure.logAnalytics' }}
```
#### Key - Barcode
```handlebars
{{ random 'Barcode.type' }}
{{ random 'Barcode.ean8' }}
{{ random 'Barcode.gtin8' }}
{{ random 'Barcode.gtin13' }}
{{ random 'Barcode.ean13' }}
{{ random 'Barcode.gtin14' }}
{{ random 'Barcode.gtin12' }}
```
#### Key - BloodType
```handlebars
{{ random 'BloodType.aboTypes' }}
{{ random 'BloodType.rhTypes' }}
{{ random 'BloodType.pTypes' }}
{{ random 'BloodType.bloodGroup' }}
```
#### Key - Book
```handlebars
{{ random 'Book.title' }}
{{ random 'Book.author' }}
{{ random 'Book.publisher' }}
{{ random 'Book.genre' }}
```
#### Key - Bool
```handlebars
{{ random 'Bool.bool' }}
```
#### Key - Business
```handlebars
{{ random 'Business.creditCardNumber' }}
{{ random 'Business.creditCardType' }}
{{ random 'Business.creditCardExpiry' }}
{{ random 'Business.securityCode' }}
```
#### Key - CNPJ
```handlebars
{{ random 'CNPJ.valid' }}
{{ random 'CNPJ.invalid' }}
```
#### Key - CPF
```handlebars
{{ random 'CPF.valid' }}
{{ random 'CPF.invalid' }}
```
#### Key - Camera
```handlebars
{{ random 'Camera.brand' }}
{{ random 'Camera.model' }}
{{ random 'Camera.brandWithModel' }}
```
#### Key - Cannabis
```handlebars
{{ random 'Cannabis.types' }}
{{ random 'Cannabis.strains' }}
{{ random 'Cannabis.terpenes' }}
{{ random 'Cannabis.categories' }}
{{ random 'Cannabis.buzzwords' }}
{{ random 'Cannabis.brands' }}
{{ random 'Cannabis.cannabinoidAbbreviations' }}
{{ random 'Cannabis.cannabinoids' }}
{{ random 'Cannabis.medicalUses' }}
{{ random 'Cannabis.healthBenefits' }}
```
#### Key - Cat
```handlebars
{{ random 'Cat.name' }}
{{ random 'Cat.breed' }}
{{ random 'Cat.registry' }}
```
#### Key - Chiquito
```handlebars
{{ random 'Chiquito.terms' }}
{{ random 'Chiquito.sentences' }}
{{ random 'Chiquito.jokes' }}
{{ random 'Chiquito.expressions' }}
```
#### Key - Code
```handlebars
{{ random 'Code.asin' }}
{{ random 'Code.isbnGs1' }}
{{ random 'Code.isbnGroup' }}
{{ random 'Code.isbn10' }}
{{ random 'Code.isbn13' }}
{{ random 'Code.imei' }}
{{ random 'Code.ean8' }}
{{ random 'Code.gtin8' }}
{{ random 'Code.gtin13' }}
{{ random 'Code.ean13' }}
{{ random 'Code.isbnRegistrant' }}
```
#### Key - Coin
```handlebars
{{ random 'Coin.flip' }}
```
#### Key - Color
```handlebars
{{ random 'Color.name' }}
{{ random 'Color.hex' }}
```
#### Key - Commerce
```handlebars
{{ random 'Commerce.brand' }}
{{ random 'Commerce.department' }}
{{ random 'Commerce.material' }}
{{ random 'Commerce.vendor' }}
{{ random 'Commerce.price' }}
{{ random 'Commerce.productName' }}
{{ random 'Commerce.promotionCode' }}
```
#### Key - Community
```handlebars
{{ random 'Community.quote' }}
{{ random 'Community.character' }}
```
#### Key - Company
```handlebars
{{ random 'Company.name' }}
{{ random 'Company.bs' }}
{{ random 'Company.suffix' }}
{{ random 'Company.url' }}
{{ random 'Company.industry' }}
{{ random 'Company.profession' }}
{{ random 'Company.buzzword' }}
{{ random 'Company.logo' }}
{{ random 'Company.catchPhrase' }}
```
#### Key - Compass
```handlebars
{{ random 'Compass.word' }}
{{ random 'Compass.azimuth' }}
{{ random 'Compass.abbreviation' }}
```
#### Key - Computer
```handlebars
{{ random 'Computer.type' }}
{{ random 'Computer.platform' }}
{{ random 'Computer.linux' }}
{{ random 'Computer.macos' }}
{{ random 'Computer.windows' }}
{{ random 'Computer.operatingSystem' }}
```
#### Key - Construction
```handlebars
{{ random 'Construction.materials' }}
{{ random 'Construction.roles' }}
{{ random 'Construction.trades' }}
{{ random 'Construction.heavyEquipment' }}
{{ random 'Construction.subcontractCategories' }}
{{ random 'Construction.standardCostCodes' }}
```
#### Key - Cosmere
```handlebars
{{ random 'Cosmere.aons' }}
{{ random 'Cosmere.shards' }}
{{ random 'Cosmere.surges' }}
{{ random 'Cosmere.metals' }}
{{ random 'Cosmere.heralds' }}
{{ random 'Cosmere.sprens' }}
{{ random 'Cosmere.shardWorlds' }}
{{ random 'Cosmere.knightsRadiant' }}
{{ random 'Cosmere.allomancers' }}
{{ random 'Cosmere.feruchemists' }}
```
#### Key - Country
```handlebars
{{ random 'Country.name' }}
{{ random 'Country.flag' }}
{{ random 'Country.currency' }}
{{ random 'Country.currencyCode' }}
{{ random 'Country.capital' }}
{{ random 'Country.countryCode2' }}
{{ random 'Country.countryCode3' }}
```
#### Key - CryptoCoin
```handlebars
{{ random 'CryptoCoin.coin' }}
```
#### Key - CultureSeries
```handlebars
{{ random 'CultureSeries.books' }}
{{ random 'CultureSeries.civs' }}
{{ random 'CultureSeries.planets' }}
{{ random 'CultureSeries.cultureShips' }}
{{ random 'CultureSeries.cultureShipClasses' }}
{{ random 'CultureSeries.cultureShipClassAbvs' }}
```
#### Key - Currency
```handlebars
{{ random 'Currency.name' }}
{{ random 'Currency.code' }}
```
#### Key - DcComics
```handlebars
{{ random 'DcComics.name' }}
{{ random 'DcComics.hero' }}
{{ random 'DcComics.heroine' }}
{{ random 'DcComics.villain' }}
{{ random 'DcComics.title' }}
```
#### Key - Demographic
```handlebars
{{ random 'Demographic.race' }}
{{ random 'Demographic.demonym' }}
{{ random 'Demographic.sex' }}
{{ random 'Demographic.educationalAttainment' }}
{{ random 'Demographic.maritalStatus' }}
```
#### Key - Device
```handlebars
{{ random 'Device.platform' }}
{{ random 'Device.modelName' }}
{{ random 'Device.serial' }}
{{ random 'Device.manufacturer' }}
```
#### Key - Disease
```handlebars
{{ random 'Disease.ophthalmologyAndOtorhinolaryngology' }}
{{ random 'Disease.neurology' }}
{{ random 'Disease.surgery' }}
{{ random 'Disease.internalDisease' }}
{{ random 'Disease.paediatrics' }}
{{ random 'Disease.gynecologyAndObstetrics' }}
{{ random 'Disease.dermatolory' }}
```
#### Key - Dog
```handlebars
{{ random 'Dog.name' }}
{{ random 'Dog.size' }}
{{ random 'Dog.breed' }}
{{ random 'Dog.sound' }}
{{ random 'Dog.memePhrase' }}
{{ random 'Dog.age' }}
{{ random 'Dog.coatLength' }}
{{ random 'Dog.gender' }}
```
#### Key - Drone
```handlebars
{{ random 'Drone.name' }}
{{ random 'Drone.iso' }}
{{ random 'Drone.weight' }}
{{ random 'Drone.flightTime' }}
{{ random 'Drone.maxSpeed' }}
{{ random 'Drone.maxAscentSpeed' }}
{{ random 'Drone.maxDescentSpeed' }}
{{ random 'Drone.maxAltitude' }}
{{ random 'Drone.maxFlightDistance' }}
{{ random 'Drone.maxWindResistance' }}
{{ random 'Drone.maxAngularVelocity' }}
{{ random 'Drone.maxTiltAngle' }}
{{ random 'Drone.operatingTemperature' }}
{{ random 'Drone.batteryCapacity' }}
{{ random 'Drone.batteryVoltage' }}
{{ random 'Drone.batteryType' }}
{{ random 'Drone.batteryWeight' }}
{{ random 'Drone.chargingTemperature' }}
{{ random 'Drone.maxChargingPower' }}
{{ random 'Drone.maxResolution' }}
{{ random 'Drone.photoFormat' }}
{{ random 'Drone.videoFormat' }}
{{ random 'Drone.maxShutterSpeed' }}
{{ random 'Drone.minShutterSpeed' }}
{{ random 'Drone.shutterSpeedUnits' }}
```
#### Key - DungeonsAndDragons
```handlebars
{{ random 'DungeonsAndDragons.alignments' }}
{{ random 'DungeonsAndDragons.cities' }}
{{ random 'DungeonsAndDragons.klasses' }}
{{ random 'DungeonsAndDragons.languages' }}
{{ random 'DungeonsAndDragons.monsters' }}
{{ random 'DungeonsAndDragons.races' }}
{{ random 'DungeonsAndDragons.backgrounds' }}
{{ random 'DungeonsAndDragons.meleeWeapons' }}
{{ random 'DungeonsAndDragons.rangedWeapons' }}
```
#### Key - Educator
```handlebars
{{ random 'Educator.course' }}
{{ random 'Educator.campus' }}
{{ random 'Educator.university' }}
{{ random 'Educator.subjectWithNumber' }}
{{ random 'Educator.secondarySchool' }}
```
#### Key - EldenRing
```handlebars
{{ random 'EldenRing.location' }}
{{ random 'EldenRing.weapon' }}
{{ random 'EldenRing.skill' }}
{{ random 'EldenRing.spell' }}
{{ random 'EldenRing.npc' }}
```
#### Key - ElectricalComponents
```handlebars
{{ random 'ElectricalComponents.active' }}
{{ random 'ElectricalComponents.passive' }}
{{ random 'ElectricalComponents.electromechanical' }}
```
#### Key - Emoji
```handlebars
{{ random 'Emoji.cat' }}
{{ random 'Emoji.smiley' }}
```
#### Key - FamousLastWords
```handlebars
{{ random 'FamousLastWords.lastWords' }}
```
#### Key - File
```handlebars
{{ random 'File.fileName' }}
{{ random 'File.extension' }}
{{ random 'File.mimeType' }}
```
#### Key - Finance
```handlebars
{{ random 'Finance.nyseTicker' }}
{{ random 'Finance.creditCard' }}
{{ random 'Finance.bic' }}
{{ random 'Finance.iban' }}
{{ random 'Finance.nasdaqTicker' }}
{{ random 'Finance.stockMarket' }}
```
#### Key - FreshPrinceOfBelAir
```handlebars
{{ random 'FreshPrinceOfBelAir.characters' }}
{{ random 'FreshPrinceOfBelAir.quotes' }}
{{ random 'FreshPrinceOfBelAir.celebrities' }}
```
#### Key - FunnyName
```handlebars
{{ random 'FunnyName.name' }}
```
#### Key - GarmentSize
```handlebars
{{ random 'GarmentSize.size' }}
```
#### Key - Gender
```handlebars
{{ random 'Gender.types' }}
{{ random 'Gender.binaryTypes' }}
{{ random 'Gender.shortBinaryTypes' }}
```
#### Key - GratefulDead
```handlebars
{{ random 'GratefulDead.players' }}
{{ random 'GratefulDead.songs' }}
```
#### Key - GreekPhilosopher
```handlebars
{{ random 'GreekPhilosopher.name' }}
{{ random 'GreekPhilosopher.quote' }}
```
#### Key - Hacker
```handlebars
{{ random 'Hacker.noun' }}
{{ random 'Hacker.ingverb' }}
{{ random 'Hacker.adjective' }}
{{ random 'Hacker.verb' }}
{{ random 'Hacker.abbreviation' }}
```
#### Key - Hashing
```handlebars
{{ random 'Hashing.md2' }}
{{ random 'Hashing.md5' }}
{{ random 'Hashing.sha1' }}
{{ random 'Hashing.sha384' }}
{{ random 'Hashing.sha256' }}
{{ random 'Hashing.sha512' }}
```
#### Key - Hipster
```handlebars
{{ random 'Hipster.word' }}
```
#### Key - Hobby
```handlebars
{{ random 'Hobby.activity' }}
```
#### Key - Hololive
```handlebars
{{ random 'Hololive.talent' }}
```
#### Key - Horse
```handlebars
{{ random 'Horse.name' }}
{{ random 'Horse.breed' }}
```
#### Key - House
```handlebars
{{ random 'House.room' }}
{{ random 'House.furniture' }}
```
#### Key - IdNumber
```handlebars
{{ random 'IdNumber.valid' }}
{{ random 'IdNumber.invalid' }}
{{ random 'IdNumber.ssnValid' }}
{{ random 'IdNumber.validPtNif' }}
{{ random 'IdNumber.validSvSeSsn' }}
{{ random 'IdNumber.validEnZaSsn' }}
{{ random 'IdNumber.inValidEnZaSsn' }}
{{ random 'IdNumber.invalidSvSeSsn' }}
{{ random 'IdNumber.singaporeanFin' }}
{{ random 'IdNumber.singaporeanFinBefore2000' }}
{{ random 'IdNumber.singaporeanUin' }}
{{ random 'IdNumber.singaporeanUinBefore2000' }}
{{ random 'IdNumber.validZhCNSsn' }}
{{ random 'IdNumber.invalidPtNif' }}
{{ random 'IdNumber.validEsMXSsn' }}
{{ random 'IdNumber.invalidEsMXSsn' }}
{{ random 'IdNumber.peselNumber' }}
```
#### Key - IndustrySegments
```handlebars
{{ random 'IndustrySegments.industry' }}
{{ random 'IndustrySegments.sector' }}
{{ random 'IndustrySegments.subSector' }}
{{ random 'IndustrySegments.superSector' }}
```
#### Key - Internet
```handlebars
{{ random 'Internet.url' }}
{{ random 'Internet.port' }}
{{ random 'Internet.image' }}
{{ random 'Internet.domainWord' }}
{{ random 'Internet.httpMethod' }}
{{ random 'Internet.macAddress' }}
{{ random 'Internet.ipV4Cidr' }}
{{ random 'Internet.ipV6Cidr' }}
{{ random 'Internet.uuidv3' }}
{{ random 'Internet.userAgent' }}
{{ random 'Internet.slug' }}
{{ random 'Internet.uuid' }}
{{ random 'Internet.domainName' }}
{{ random 'Internet.password' }}
{{ random 'Internet.emailAddress' }}
{{ random 'Internet.safeEmailAddress' }}
{{ random 'Internet.ipV4Address' }}
{{ random 'Internet.getIpV4Address' }}
{{ random 'Internet.privateIpV4Address' }}
{{ random 'Internet.getPrivateIpV4Address' }}
{{ random 'Internet.publicIpV4Address' }}
{{ random 'Internet.getPublicIpV4Address' }}
{{ random 'Internet.ipV6Address' }}
{{ random 'Internet.getIpV6Address' }}
{{ random 'Internet.botUserAgentAny' }}
{{ random 'Internet.domainSuffix' }}
```
#### Key - Job
```handlebars
{{ random 'Job.position' }}
{{ random 'Job.field' }}
{{ random 'Job.seniority' }}
{{ random 'Job.keySkills' }}
{{ random 'Job.title' }}
```
#### Key - Kpop
```handlebars
{{ random 'Kpop.iGroups' }}
{{ random 'Kpop.iiGroups' }}
{{ random 'Kpop.iiiGroups' }}
{{ random 'Kpop.girlGroups' }}
{{ random 'Kpop.boyBands' }}
{{ random 'Kpop.solo' }}
```
#### Key - Lorem
```handlebars
{{ random 'Lorem.words' }}
{{ random 'Lorem.word' }}
{{ random 'Lorem.character' }}
{{ random 'Lorem.sentence' }}
{{ random 'Lorem.paragraph' }}
{{ random 'Lorem.characters' }}
```
#### Key - Marketing
```handlebars
{{ random 'Marketing.buzzwords' }}
```
#### Key - Matz
```handlebars
{{ random 'Matz.quote' }}
```
#### Key - Mbti
```handlebars
{{ random 'Mbti.name' }}
{{ random 'Mbti.type' }}
{{ random 'Mbti.personage' }}
{{ random 'Mbti.merit' }}
{{ random 'Mbti.weakness' }}
{{ random 'Mbti.characteristic' }}
```
#### Key - Measurement
```handlebars
{{ random 'Measurement.length' }}
{{ random 'Measurement.height' }}
{{ random 'Measurement.weight' }}
{{ random 'Measurement.volume' }}
{{ random 'Measurement.metricHeight' }}
{{ random 'Measurement.metricLength' }}
{{ random 'Measurement.metricVolume' }}
{{ random 'Measurement.metricWeight' }}
```
#### Key - Medical
```handlebars
{{ random 'Medical.symptoms' }}
{{ random 'Medical.medicineName' }}
{{ random 'Medical.diseaseName' }}
{{ random 'Medical.hospitalName' }}
{{ random 'Medical.diagnosisCode' }}
{{ random 'Medical.procedureCode' }}
```
#### Key - Military
```handlebars
{{ random 'Military.armyRank' }}
{{ random 'Military.navyRank' }}
{{ random 'Military.marinesRank' }}
{{ random 'Military.airForceRank' }}
{{ random 'Military.dodPaygrade' }}
```
#### Key - Money
```handlebars
{{ random 'Money.currency' }}
{{ random 'Money.currencyCode' }}
```
#### Key - Mood
```handlebars
{{ random 'Mood.feeling' }}
{{ random 'Mood.emotion' }}
{{ random 'Mood.tone' }}
```
#### Key - Mountain
```handlebars
{{ random 'Mountain.name' }}
{{ random 'Mountain.range' }}
```
#### Key - Mountaineering
```handlebars
{{ random 'Mountaineering.mountaineer' }}
```
#### Key - Music
```handlebars
{{ random 'Music.key' }}
{{ random 'Music.instrument' }}
{{ random 'Music.chord' }}
{{ random 'Music.genre' }}
```
#### Key - Name
```handlebars
{{ random 'Name.name' }}
{{ random 'Name.prefix' }}
{{ random 'Name.suffix' }}
{{ random 'Name.lastName' }}
{{ random 'Name.fullName' }}
{{ random 'Name.firstName' }}
{{ random 'Name.title' }}
{{ random 'Name.username' }}
{{ random 'Name.nameWithMiddle' }}
```
#### Key - Nation
```handlebars
{{ random 'Nation.flag' }}
{{ random 'Nation.language' }}
{{ random 'Nation.isoCountry' }}
{{ random 'Nation.nationality' }}
{{ random 'Nation.capitalCity' }}
{{ random 'Nation.isoLanguage' }}
```
#### Key - NatoPhoneticAlphabet
```handlebars
{{ random 'NatoPhoneticAlphabet.codeWord' }}
```
#### Key - Nigeria
```handlebars
{{ random 'Nigeria.name' }}
{{ random 'Nigeria.places' }}
{{ random 'Nigeria.schools' }}
{{ random 'Nigeria.food' }}
{{ random 'Nigeria.celebrities' }}
```
#### Key - Number
```handlebars
{{ random 'Number.digit' }}
{{ random 'Number.negative' }}
{{ random 'Number.positive' }}
{{ random 'Number.randomDigit' }}
{{ random 'Number.randomDigitNotZero' }}
{{ random 'Number.randomNumber' }}
```
#### Key - Passport
```handlebars
{{ random 'Passport.valid' }}
```
#### Key - PhoneNumber
```handlebars
{{ random 'PhoneNumber.extension' }}
{{ random 'PhoneNumber.cellPhone' }}
{{ random 'PhoneNumber.phoneNumberInternational' }}
{{ random 'PhoneNumber.phoneNumberNational' }}
{{ random 'PhoneNumber.subscriberNumber' }}
{{ random 'PhoneNumber.phoneNumber' }}
```
#### Key - Photography
```handlebars
{{ random 'Photography.iso' }}
{{ random 'Photography.brand' }}
{{ random 'Photography.genre' }}
{{ random 'Photography.lens' }}
{{ random 'Photography.imageTag' }}
{{ random 'Photography.aperture' }}
{{ random 'Photography.shutter' }}
{{ random 'Photography.camera' }}
{{ random 'Photography.term' }}
```
#### Key - ProgrammingLanguage
```handlebars
{{ random 'ProgrammingLanguage.name' }}
{{ random 'ProgrammingLanguage.creator' }}
```
#### Key - Relationship
```handlebars
{{ random 'Relationship.parent' }}
{{ random 'Relationship.inLaw' }}
{{ random 'Relationship.spouse' }}
{{ random 'Relationship.sibling' }}
```
#### Key - Restaurant
```handlebars
{{ random 'Restaurant.name' }}
{{ random 'Restaurant.type' }}
{{ random 'Restaurant.description' }}
{{ random 'Restaurant.namePrefix' }}
{{ random 'Restaurant.nameSuffix' }}
{{ random 'Restaurant.review' }}
```
#### Key - Robin
```handlebars
{{ random 'Robin.quote' }}
```
#### Key - RockBand
```handlebars
{{ random 'RockBand.name' }}
```
#### Key - Science
```handlebars
{{ random 'Science.element' }}
{{ random 'Science.unit' }}
{{ random 'Science.scientist' }}
{{ random 'Science.tool' }}
{{ random 'Science.quark' }}
{{ random 'Science.leptons' }}
{{ random 'Science.bosons' }}
{{ random 'Science.elementSymbol' }}
```
#### Key - Shakespeare
```handlebars
{{ random 'Shakespeare.hamletQuote' }}
{{ random 'Shakespeare.asYouLikeItQuote' }}
{{ random 'Shakespeare.kingRichardIIIQuote' }}
{{ random 'Shakespeare.romeoAndJulietQuote' }}
```
#### Key - Sip
```handlebars
{{ random 'Sip.method' }}
{{ random 'Sip.rtpPort' }}
{{ random 'Sip.bodyString' }}
{{ random 'Sip.bodyBytes' }}
{{ random 'Sip.contentType' }}
{{ random 'Sip.messagingPort' }}
{{ random 'Sip.provisionalResponseCode' }}
{{ random 'Sip.successResponseCode' }}
{{ random 'Sip.redirectResponseCode' }}
{{ random 'Sip.clientErrorResponseCode' }}
{{ random 'Sip.serverErrorResponseCode' }}
{{ random 'Sip.globalErrorResponseCode' }}
{{ random 'Sip.provisionalResponsePhrase' }}
{{ random 'Sip.successResponsePhrase' }}
{{ random 'Sip.redirectResponsePhrase' }}
{{ random 'Sip.clientErrorResponsePhrase' }}
{{ random 'Sip.serverErrorResponsePhrase' }}
{{ random 'Sip.globalErrorResponsePhrase' }}
{{ random 'Sip.nameAddress' }}
```
#### Key - Size
```handlebars
{{ random 'Size.adjective' }}
```
#### Key - SlackEmoji
```handlebars
{{ random 'SlackEmoji.people' }}
{{ random 'SlackEmoji.nature' }}
{{ random 'SlackEmoji.custom' }}
{{ random 'SlackEmoji.activity' }}
{{ random 'SlackEmoji.emoji' }}
{{ random 'SlackEmoji.foodAndDrink' }}
{{ random 'SlackEmoji.celebration' }}
{{ random 'SlackEmoji.travelAndPlaces' }}
{{ random 'SlackEmoji.objectsAndSymbols' }}
```
#### Key - Space
```handlebars
{{ random 'Space.planet' }}
{{ random 'Space.moon' }}
{{ random 'Space.galaxy' }}
{{ random 'Space.nebula' }}
{{ random 'Space.star' }}
{{ random 'Space.agency' }}
{{ random 'Space.meteorite' }}
{{ random 'Space.company' }}
{{ random 'Space.starCluster' }}
{{ random 'Space.constellation' }}
{{ random 'Space.agencyAbbreviation' }}
{{ random 'Space.nasaSpaceCraft' }}
{{ random 'Space.distanceMeasurement' }}
```
#### Key - Stock
```handlebars
{{ random 'Stock.nsdqSymbol' }}
{{ random 'Stock.nyseSymbol' }}
```
#### Key - Subscription
```handlebars
{{ random 'Subscription.plans' }}
{{ random 'Subscription.statuses' }}
{{ random 'Subscription.paymentMethods' }}
{{ random 'Subscription.subscriptionTerms' }}
{{ random 'Subscription.paymentTerms' }}
```
#### Key - Superhero
```handlebars
{{ random 'Superhero.name' }}
{{ random 'Superhero.prefix' }}
{{ random 'Superhero.suffix' }}
{{ random 'Superhero.descriptor' }}
{{ random 'Superhero.power' }}
```
#### Key - Team
```handlebars
{{ random 'Team.name' }}
{{ random 'Team.state' }}
{{ random 'Team.sport' }}
{{ random 'Team.creature' }}
```
#### Key - Text
```handlebars
{{ random 'Text.text' }}
{{ random 'Text.character' }}
{{ random 'Text.uppercaseCharacter' }}
{{ random 'Text.lowercaseCharacter' }}
```
#### Key - Tron
```handlebars
{{ random 'Tron.location' }}
{{ random 'Tron.quote' }}
{{ random 'Tron.character' }}
{{ random 'Tron.game' }}
{{ random 'Tron.tagline' }}
{{ random 'Tron.vehicle' }}
{{ random 'Tron.alternateCharacterSpelling' }}
```
#### Key - Twitter
```handlebars
{{ random 'Twitter.userName' }}
{{ random 'Twitter.userId' }}
```
#### Key - University
```handlebars
{{ random 'University.name' }}
{{ random 'University.prefix' }}
{{ random 'University.suffix' }}
```
#### Key - Vehicle
```handlebars
{{ random 'Vehicle.make' }}
{{ random 'Vehicle.color' }}
{{ random 'Vehicle.style' }}
{{ random 'Vehicle.vin' }}
{{ random 'Vehicle.upholstery' }}
{{ random 'Vehicle.driveType' }}
{{ random 'Vehicle.fuelType' }}
{{ random 'Vehicle.carType' }}
{{ random 'Vehicle.engine' }}
{{ random 'Vehicle.carOptions' }}
{{ random 'Vehicle.doors' }}
{{ random 'Vehicle.model' }}
{{ random 'Vehicle.manufacturer' }}
{{ random 'Vehicle.makeAndModel' }}
{{ random 'Vehicle.upholsteryColor' }}
{{ random 'Vehicle.upholsteryFabric' }}
{{ random 'Vehicle.transmission' }}
{{ random 'Vehicle.standardSpecs' }}
{{ random 'Vehicle.licensePlate' }}
```
#### Key - Verb
```handlebars
{{ random 'Verb.base' }}
{{ random 'Verb.ingForm' }}
{{ random 'Verb.past' }}
{{ random 'Verb.pastParticiple' }}
{{ random 'Verb.simplePresent' }}
```
#### Key - Weather
```handlebars
{{ random 'Weather.description' }}
{{ random 'Weather.temperatureCelsius' }}
{{ random 'Weather.temperatureFahrenheit' }}
```
#### Key - Yoda
```handlebars
{{ random 'Yoda.quote' }}
```
### Category - Food
#### Key - Beer
```handlebars
{{ random 'Beer.name' }}
{{ random 'Beer.style' }}
{{ random 'Beer.hop' }}
{{ random 'Beer.yeast' }}
{{ random 'Beer.malt' }}
```
#### Key - Coffee
```handlebars
{{ random 'Coffee.descriptor' }}
{{ random 'Coffee.name1' }}
{{ random 'Coffee.name2' }}
{{ random 'Coffee.body' }}
{{ random 'Coffee.country' }}
{{ random 'Coffee.region' }}
{{ random 'Coffee.variety' }}
{{ random 'Coffee.notes' }}
{{ random 'Coffee.blendName' }}
{{ random 'Coffee.intensifier' }}
```
#### Key - Dessert
```handlebars
{{ random 'Dessert.variety' }}
{{ random 'Dessert.topping' }}
{{ random 'Dessert.flavor' }}
```
#### Key - Food
```handlebars
{{ random 'Food.ingredient' }}
{{ random 'Food.spice' }}
{{ random 'Food.dish' }}
{{ random 'Food.fruit' }}
{{ random 'Food.vegetable' }}
{{ random 'Food.sushi' }}
{{ random 'Food.measurement' }}
```
#### Key - Tea
```handlebars
{{ random 'Tea.type' }}
{{ random 'Tea.variety' }}
```
### Category - Movie
#### Key - AquaTeenHungerForce
```handlebars
{{ random 'AquaTeenHungerForce.character' }}
```
#### Key - Avatar
```handlebars
{{ random 'Avatar.image' }}
```
#### Key - Babylon5
```handlebars
{{ random 'Babylon5.quote' }}
{{ random 'Babylon5.character' }}
```
#### Key - BackToTheFuture
```handlebars
{{ random 'BackToTheFuture.quote' }}
{{ random 'BackToTheFuture.date' }}
{{ random 'BackToTheFuture.character' }}
```
#### Key - BigBangTheory
```handlebars
{{ random 'BigBangTheory.quote' }}
{{ random 'BigBangTheory.character' }}
```
#### Key - BojackHorseman
```handlebars
{{ random 'BojackHorseman.characters' }}
{{ random 'BojackHorseman.quotes' }}
{{ random 'BojackHorseman.tongueTwisters' }}
```
#### Key - BossaNova
```handlebars
{{ random 'BossaNova.artist' }}
{{ random 'BossaNova.song' }}
```
#### Key - BreakingBad
```handlebars
{{ random 'BreakingBad.character' }}
{{ random 'BreakingBad.episode' }}
```
#### Key - BrooklynNineNine
```handlebars
{{ random 'BrooklynNineNine.characters' }}
{{ random 'BrooklynNineNine.quotes' }}
```
#### Key - Buffy
```handlebars
{{ random 'Buffy.characters' }}
{{ random 'Buffy.quotes' }}
{{ random 'Buffy.bigBads' }}
{{ random 'Buffy.episodes' }}
{{ random 'Buffy.celebrities' }}
```
#### Key - ChuckNorris
```handlebars
{{ random 'ChuckNorris.fact' }}
```
#### Key - DarkSoul
```handlebars
{{ random 'DarkSoul.classes' }}
{{ random 'DarkSoul.stats' }}
{{ random 'DarkSoul.covenants' }}
{{ random 'DarkSoul.shield' }}
```
#### Key - Departed
```handlebars
{{ random 'Departed.quote' }}
{{ random 'Departed.character' }}
{{ random 'Departed.actor' }}
```
#### Key - DetectiveConan
```handlebars
{{ random 'DetectiveConan.characters' }}
{{ random 'DetectiveConan.gadgets' }}
{{ random 'DetectiveConan.vehicles' }}
```
#### Key - DoctorWho
```handlebars
{{ random 'DoctorWho.quote' }}
{{ random 'DoctorWho.character' }}
{{ random 'DoctorWho.species' }}
{{ random 'DoctorWho.actor' }}
{{ random 'DoctorWho.villain' }}
{{ random 'DoctorWho.doctor' }}
{{ random 'DoctorWho.catchPhrase' }}
```
#### Key - Doraemon
```handlebars
{{ random 'Doraemon.location' }}
{{ random 'Doraemon.character' }}
{{ random 'Doraemon.gadget' }}
```
#### Key - DragonBall
```handlebars
{{ random 'DragonBall.character' }}
```
#### Key - DumbAndDumber
```handlebars
{{ random 'DumbAndDumber.quote' }}
{{ random 'DumbAndDumber.character' }}
{{ random 'DumbAndDumber.actor' }}
```
#### Key - Dune
```handlebars
{{ random 'Dune.quote' }}
{{ random 'Dune.character' }}
{{ random 'Dune.title' }}
{{ random 'Dune.planet' }}
{{ random 'Dune.saying' }}
```
#### Key - FamilyGuy
```handlebars
{{ random 'FamilyGuy.location' }}
{{ random 'FamilyGuy.quote' }}
{{ random 'FamilyGuy.character' }}
```
#### Key - FinalSpace
```handlebars
{{ random 'FinalSpace.quote' }}
{{ random 'FinalSpace.character' }}
{{ random 'FinalSpace.vehicle' }}
```
#### Key - Friends
```handlebars
{{ random 'Friends.location' }}
{{ random 'Friends.quote' }}
{{ random 'Friends.character' }}
```
#### Key - FullmetalAlchemist
```handlebars
{{ random 'FullmetalAlchemist.country' }}
{{ random 'FullmetalAlchemist.character' }}
{{ random 'FullmetalAlchemist.city' }}
```
#### Key - GameOfThrones
```handlebars
{{ random 'GameOfThrones.quote' }}
{{ random 'GameOfThrones.character' }}
{{ random 'GameOfThrones.city' }}
{{ random 'GameOfThrones.house' }}
{{ random 'GameOfThrones.dragon' }}
```
#### Key - Ghostbusters
```handlebars
{{ random 'Ghostbusters.quote' }}
{{ random 'Ghostbusters.character' }}
{{ random 'Ghostbusters.actor' }}
```
#### Key - HarryPotter
```handlebars
{{ random 'HarryPotter.location' }}
{{ random 'HarryPotter.quote' }}
{{ random 'HarryPotter.character' }}
{{ random 'HarryPotter.spell' }}
{{ random 'HarryPotter.book' }}
{{ random 'HarryPotter.house' }}
```
#### Key - HeyArnold
```handlebars
{{ random 'HeyArnold.locations' }}
{{ random 'HeyArnold.characters' }}
{{ random 'HeyArnold.quotes' }}
```
#### Key - HitchhikersGuideToTheGalaxy
```handlebars
{{ random 'HitchhikersGuideToTheGalaxy.location' }}
{{ random 'HitchhikersGuideToTheGalaxy.quote' }}
{{ random 'HitchhikersGuideToTheGalaxy.character' }}
{{ random 'HitchhikersGuideToTheGalaxy.species' }}
{{ random 'HitchhikersGuideToTheGalaxy.planet' }}
{{ random 'HitchhikersGuideToTheGalaxy.starship' }}
{{ random 'HitchhikersGuideToTheGalaxy.marvinQuote' }}
```
#### Key - Hobbit
```handlebars
{{ random 'Hobbit.location' }}
{{ random 'Hobbit.quote' }}
{{ random 'Hobbit.character' }}
{{ random 'Hobbit.thorinsCompany' }}
```
#### Key - HowIMetYourMother
```handlebars
{{ random 'HowIMetYourMother.quote' }}
{{ random 'HowIMetYourMother.character' }}
{{ random 'HowIMetYourMother.highFive' }}
{{ random 'HowIMetYourMother.catchPhrase' }}
```
#### Key - Kaamelott
```handlebars
{{ random 'Kaamelott.quote' }}
{{ random 'Kaamelott.character' }}
```
#### Key - Lebowski
```handlebars
{{ random 'Lebowski.quote' }}
{{ random 'Lebowski.character' }}
{{ random 'Lebowski.actor' }}
```
#### Key - LordOfTheRings
```handlebars
{{ random 'LordOfTheRings.location' }}
{{ random 'LordOfTheRings.character' }}
```
#### Key - MoneyHeist
```handlebars
{{ random 'MoneyHeist.quote' }}
{{ random 'MoneyHeist.character' }}
{{ random 'MoneyHeist.heist' }}
```
#### Key - Movie
```handlebars
{{ random 'Movie.quote' }}
```
#### Key - OnePiece
```handlebars
{{ random 'OnePiece.location' }}
{{ random 'OnePiece.quote' }}
{{ random 'OnePiece.character' }}
{{ random 'OnePiece.sea' }}
{{ random 'OnePiece.island' }}
{{ random 'OnePiece.akumasNoMi' }}
```
#### Key - OscarMovie
```handlebars
{{ random 'OscarMovie.quote' }}
{{ random 'OscarMovie.getYear' }}
{{ random 'OscarMovie.character' }}
{{ random 'OscarMovie.actor' }}
{{ random 'OscarMovie.getChoice' }}
{{ random 'OscarMovie.movieName' }}
{{ random 'OscarMovie.releaseDate' }}
```
#### Key - Pokemon
```handlebars
{{ random 'Pokemon.name' }}
{{ random 'Pokemon.type' }}
{{ random 'Pokemon.location' }}
{{ random 'Pokemon.move' }}
```
#### Key - PrincessBride
```handlebars
{{ random 'PrincessBride.quote' }}
{{ random 'PrincessBride.character' }}
```
#### Key - ResidentEvil
```handlebars
{{ random 'ResidentEvil.location' }}
{{ random 'ResidentEvil.character' }}
{{ random 'ResidentEvil.equipment' }}
{{ random 'ResidentEvil.creature' }}
{{ random 'ResidentEvil.biologicalAgent' }}
```
#### Key - RickAndMorty
```handlebars
{{ random 'RickAndMorty.location' }}
{{ random 'RickAndMorty.quote' }}
{{ random 'RickAndMorty.character' }}
```
#### Key - RuPaulDragRace
```handlebars
{{ random 'RuPaulDragRace.quote' }}
{{ random 'RuPaulDragRace.queen' }}
```
#### Key - Seinfeld
```handlebars
{{ random 'Seinfeld.quote' }}
{{ random 'Seinfeld.character' }}
{{ random 'Seinfeld.business' }}
```
#### Key - Simpsons
```handlebars
{{ random 'Simpsons.location' }}
{{ random 'Simpsons.quote' }}
{{ random 'Simpsons.character' }}
```
#### Key - StarTrek
```handlebars
{{ random 'StarTrek.location' }}
{{ random 'StarTrek.character' }}
{{ random 'StarTrek.species' }}
{{ random 'StarTrek.villain' }}
{{ random 'StarTrek.klingon' }}
```
#### Key - StarWars
```handlebars
{{ random 'StarWars.character' }}
{{ random 'StarWars.species' }}
{{ random 'StarWars.planets' }}
{{ random 'StarWars.quotes' }}
{{ random 'StarWars.callSign' }}
{{ random 'StarWars.vehicles' }}
{{ random 'StarWars.droids' }}
{{ random 'StarWars.alternateCharacterSpelling' }}
{{ random 'StarWars.wookieWords' }}
```
#### Key - StudioGhibli
```handlebars
{{ random 'StudioGhibli.quote' }}
{{ random 'StudioGhibli.character' }}
{{ random 'StudioGhibli.movie' }}
```
#### Key - TheItCrowd
```handlebars
{{ random 'TheItCrowd.characters' }}
{{ random 'TheItCrowd.quotes' }}
{{ random 'TheItCrowd.actors' }}
{{ random 'TheItCrowd.emails' }}
```
#### Key - TwinPeaks
```handlebars
{{ random 'TwinPeaks.location' }}
{{ random 'TwinPeaks.quote' }}
{{ random 'TwinPeaks.character' }}
```
#### Key - Witcher
```handlebars
{{ random 'Witcher.location' }}
{{ random 'Witcher.sign' }}
{{ random 'Witcher.quote' }}
{{ random 'Witcher.character' }}
{{ random 'Witcher.witcher' }}
{{ random 'Witcher.school' }}
{{ random 'Witcher.monster' }}
{{ random 'Witcher.potion' }}
{{ random 'Witcher.book' }}
```
### Category - Sport
#### Key - Baseball
```handlebars
{{ random 'Baseball.positions' }}
{{ random 'Baseball.players' }}
{{ random 'Baseball.teams' }}
{{ random 'Baseball.coaches' }}
```
#### Key - Basketball
```handlebars
{{ random 'Basketball.positions' }}
{{ random 'Basketball.players' }}
{{ random 'Basketball.teams' }}
{{ random 'Basketball.coaches' }}
```
#### Key - Cricket
```handlebars
{{ random 'Cricket.formats' }}
{{ random 'Cricket.players' }}
{{ random 'Cricket.teams' }}
{{ random 'Cricket.tournaments' }}
```
#### Key - EnglandFootBall
```handlebars
{{ random 'EnglandFootBall.team' }}
{{ random 'EnglandFootBall.league' }}
```
#### Key - Football
```handlebars
{{ random 'Football.positions' }}
{{ random 'Football.players' }}
{{ random 'Football.teams' }}
{{ random 'Football.coaches' }}
{{ random 'Football.competitions' }}
```
#### Key - Formula1
```handlebars
{{ random 'Formula1.team' }}
{{ random 'Formula1.driver' }}
{{ random 'Formula1.circuit' }}
{{ random 'Formula1.grandPrix' }}
```
#### Key - Volleyball
```handlebars
{{ random 'Volleyball.position' }}
{{ random 'Volleyball.team' }}
{{ random 'Volleyball.player' }}
{{ random 'Volleyball.coach' }}
{{ random 'Volleyball.formation' }}
```
### Category - Video Games
#### Key - Battlefield1
```handlebars
{{ random 'Battlefield1.map' }}
{{ random 'Battlefield1.classes' }}
{{ random 'Battlefield1.weapon' }}
{{ random 'Battlefield1.vehicle' }}
{{ random 'Battlefield1.faction' }}
```
#### Key - ClashOfClans
```handlebars
{{ random 'ClashOfClans.troop' }}
{{ random 'ClashOfClans.rank' }}
{{ random 'ClashOfClans.defensiveBuilding' }}
```
#### Key - Control
```handlebars
{{ random 'Control.location' }}
{{ random 'Control.quote' }}
{{ random 'Control.character' }}
{{ random 'Control.hiss' }}
{{ random 'Control.theBoard' }}
{{ random 'Control.objectOfPower' }}
{{ random 'Control.alteredItem' }}
{{ random 'Control.alteredWorldEvent' }}
```
#### Key - ElderScrolls
```handlebars
{{ random 'ElderScrolls.quote' }}
{{ random 'ElderScrolls.lastName' }}
{{ random 'ElderScrolls.region' }}
{{ random 'ElderScrolls.race' }}
{{ random 'ElderScrolls.creature' }}
{{ random 'ElderScrolls.firstName' }}
{{ random 'ElderScrolls.city' }}
{{ random 'ElderScrolls.dragon' }}
```
#### Key - Esports
```handlebars
{{ random 'Esports.event' }}
{{ random 'Esports.game' }}
{{ random 'Esports.team' }}
{{ random 'Esports.player' }}
{{ random 'Esports.league' }}
```
#### Key - Fallout
```handlebars
{{ random 'Fallout.location' }}
{{ random 'Fallout.quote' }}
{{ random 'Fallout.character' }}
{{ random 'Fallout.faction' }}
```
#### Key - Hearthstone
```handlebars
{{ random 'Hearthstone.wildRank' }}
{{ random 'Hearthstone.mainProfession' }}
{{ random 'Hearthstone.mainCharacter' }}
{{ random 'Hearthstone.mainPattern' }}
{{ random 'Hearthstone.battlegroundsScore' }}
{{ random 'Hearthstone.standardRank' }}
```
#### Key - HeroesOfTheStorm
```handlebars
{{ random 'HeroesOfTheStorm.quote' }}
{{ random 'HeroesOfTheStorm.hero' }}
{{ random 'HeroesOfTheStorm.heroClass' }}
{{ random 'HeroesOfTheStorm.battleground' }}
```
#### Key - LeagueOfLegends
```handlebars
{{ random 'LeagueOfLegends.location' }}
{{ random 'LeagueOfLegends.quote' }}
{{ random 'LeagueOfLegends.rank' }}
{{ random 'LeagueOfLegends.champion' }}
{{ random 'LeagueOfLegends.masteries' }}
{{ random 'LeagueOfLegends.summonerSpell' }}
```
#### Key - MassEffect
```handlebars
{{ random 'MassEffect.quote' }}
{{ random 'MassEffect.character' }}
{{ random 'MassEffect.planet' }}
{{ random 'MassEffect.specie' }}
{{ random 'MassEffect.cluster' }}
```
#### Key - Minecraft
```handlebars
{{ random 'Minecraft.itemName' }}
{{ random 'Minecraft.tileName' }}
{{ random 'Minecraft.entityName' }}
{{ random 'Minecraft.animalName' }}
{{ random 'Minecraft.monsterName' }}
{{ random 'Minecraft.tileItemName' }}
```
#### Key - Overwatch
```handlebars
{{ random 'Overwatch.location' }}
{{ random 'Overwatch.quote' }}
{{ random 'Overwatch.hero' }}
```
#### Key - SoulKnight
```handlebars
{{ random 'SoulKnight.characters' }}
{{ random 'SoulKnight.buffs' }}
{{ random 'SoulKnight.statues' }}
{{ random 'SoulKnight.weapons' }}
{{ random 'SoulKnight.bosses' }}
{{ random 'SoulKnight.enemies' }}
```
#### Key - StarCraft
```handlebars
{{ random 'StarCraft.unit' }}
{{ random 'StarCraft.character' }}
{{ random 'StarCraft.planet' }}
{{ random 'StarCraft.building' }}
```
#### Key - SuperMario
```handlebars
{{ random 'SuperMario.locations' }}
{{ random 'SuperMario.games' }}
{{ random 'SuperMario.characters' }}
```
#### Key - Touhou
```handlebars
{{ random 'Touhou.trackName' }}
{{ random 'Touhou.gameName' }}
{{ random 'Touhou.characterName' }}
{{ random 'Touhou.characterFirstName' }}
{{ random 'Touhou.characterLastName' }}
```
#### Key - Zelda
```handlebars
{{ random 'Zelda.character' }}
{{ random 'Zelda.game' }}
```
### Response Templating - Random Values
Source: https://docs.wiremock.io/response-templating/random-values
WireMock Cloud provides two random value helpers - `randomValue` and `pickRandom`.
## Random strings
The `randomValue` helper generates random strings of a specific type and length.
Optionally, values containing alphabetic characters can be made upper case via the `uppercase` parameter.
```handlebars
{{randomValue length=33 type='ALPHANUMERIC'}}
{{randomValue length=12 type='ALPHANUMERIC' uppercase=true}}
{{randomValue length=55 type='ALPHABETIC'}}
{{randomValue length=27 type='ALPHABETIC' uppercase=true}}
{{randomValue length=10 type='NUMERIC'}}
{{randomValue length=5 type='ALPHANUMERIC_AND_SYMBOLS'}}
{{randomValue length=5 type='HEXADECIMAL' uppercase=true}}
{{randomValue type='UUID'}}
```
## Random numbers
While the `randomValue` helper can generate a number as a string when type `NUMERIC` is requested,
sometimes it can be useful to emit an actual typed number with the ability to control
lower and upper bounds. Working with numbers this way supports further processing
with the `math` helper or can serve as input to the `range` helper, among other uses.
The `randomInt` helper emits random integers with one, both or neither bound specified.
```handlebars
{{randomInt}}
{{randomInt lower=5 upper=9}}
{{randomInt upper=54323}}
{{randomInt lower=-24}}
```
Likewise `randomDecimal` will emit random decimals:
```handlebars
{{randomDecimal}}
{{randomDecimal lower=-10.1 upper=-0.9}}
{{randomDecimal upper=12.5}}
{{randomDecimal lower=-24.01}}
```
## Pick random
The `pickRandom` helper randomly selects a value from its parameters.
If the first parameter is a collection then the value will be randomly selected
from within this:
```handlebars
{{#parseJson 'numberList'}}
[1,2,3]
{{/parseJson}}
{{pickRandom numberList}} // One of 1, 2 or 3
```
Otherwise a value will be picked from the list of parameters provided:
```handlebars
{{pickRandom '1' '2' '3'}} // One of 1, 2 or 3
```
If you desire multiple unique elements to be randomly pulled from the list, a `count` option can be supplied to the
helper.
In this case, the result will be a list, instead of a single value.
For example, the following template:
```
{{pickRandom 1 2 3 4 5 count=3}}
```
will produce a list similar to the following:
```
[3, 5, 2]
```
### Response Templating - String Encodings
Source: https://docs.wiremock.io/response-templating/string-encodings
WireMock Cloud provides several helpers for encoding and decoding values to/from various
formats.
## Base64
The `base64` helper encodes and decodes Base64:
```handlebars
{{{base64 request.headers.X-Plain-Header}}}
{{{base64 request.headers.X-Plain-Header padding=false}}}
{{{base64 request.headers.X-Encoded-Header decode=true}}}
{{#base64}}Content to encode{{/base64}}
{{#base64 decode=true}}Q29udGVudCB0byBkZWNvZGUK{{/base64}}
```
## URLs
The `urlEncode` helper encode and decode values according to the [HTTP URL encoding standard](https://en.wikipedia.org/wiki/Percent-encoding).
```handlebars
{{{urlEncode request.headers.X-Plain-Header}}}
{{{urlEncode request.headers.X-Encoded-Header decode=true}}}
{{#urlEncode}}Content to encode{{/urlEncode}}
{{#urlEncode decode=true}}Content%20to%20decode{{/urlEncode}}
```
## Forms
The `formData` helper parses its input as an HTTP form, returning an object containing the individual fields as attributes.
The helper takes the input string and variable name as its required parameters, with an optional `urlDecode` parameter
indicating that values should be URL decoded.
The following example will parse the request body as a form, then output a single field `formField3`:
```handlebars
{{formData request.body 'form' urlDecode=true}}{{{form.formField3}}
```
If the form submitted has multiple values for a given field, these can be accessed by index:
```handlebars
{{formData request.body 'form' urlDecode=true}}}{{{form.multiValueField.1}}, {{{form.multiValueField.2}}
{{formData request.body 'form' urlDecode=true}}}{{{form.multiValueField.first}}, {{{form.multiValueField.last}}
```
### Response Templating - String Helpers
Source: https://docs.wiremock.io/response-templating/string-helpers
WireMock Cloud provides a set of string manipulation helpers.
## Regular expression extract
The `regexExtract` helper supports extraction of values matching a regular expression from a string.
A single value can be extracted like this:
```handlebars
{{regexExtract request.body '[A-Z]+'}}"
```
Regex groups can be used to extract multiple parts into an object for later use (the last parameter is a variable name to which the object will be assigned):
```handlebars
{{regexExtract request.body '([a-z]+)-([A-Z]+)-([0-9]+)' 'parts'}}
{{parts.0}},{{parts.1}},{{parts.2}}
```
Optionally, a default value can be specified for when there is no match. When the regex does not match and no default is specified, an error will be thrown instead.
```handlebars
{{regexExtract 'abc' '[0-9]+' default='my default value'}}
```
## Regular expression replace
The `regexReplace` helper replaces all matches of a regular expression in a string with a replacement value.
```handlebars
{{regexReplace 'a1b2c3' '[0-9]' '-'}} // a-b-c-
```
Capture groups in the pattern can be referenced in the replacement using `$1`, `$2` etc:
```handlebars
{{regexReplace 'user@host' '(\w+)@(\w+)' '$2:$1'}} // host:user
```
## String transformation helpers
### Trim
Use the `trim` helper to remove whitespace from the start and end of the input:
```handlebars
{{trim request.headers.X-Padded-Header}} // Inline
{{#trim}} // Block
Some stuff with whitespace
{{/trim}}
```
### Abbreviate
`abbreviate` truncates a string if it is longer than the specified number of characters.
Truncated strings will end with a translatable ellipsis sequence ("...").
For instance the following template:
```handlebars
{{abbreviate 'Mocking APIs helps you develop faster' 21 }} // Mocking APIs helps...
```
### Capitalisation
`capitalize` will make the first letter of each word in the passed string a capital e.g.
```handlebars
{{capitalize 'mock my stuff'}} // Mock My Stuff
```
`capitalizeFirst` will capitalise the first character of the value passed e.g.
```handlebars
{{capitalizeFirst 'mock my stuff'}} // Mock my stuff
```
### Center
`center` centers the value in a field of a given width e.g.
```handlebars
{{center 'hello' size=21}}
```
will output:
```
hello
```
You can also specify the padding character e.g.
```handlebars
{{center 'hello' size=21 pad='#'}}
```
will output:
```
########hello########
```
### Cut
`cut` removes all instances of the parameter from the given string.
```handlebars
{{cut 'mocking, stubbing, faults' ','}} // mocking stubbing faults
```
### Default if empty
`defaultIfEmpty` outputs the passed value if it is not empty, or the default otherwise e.g.
```handlebars
{{defaultIfEmpty 'my value' 'default'}} // my value
{{defaultIfEmpty '' 'default'}} // default
```
### Join
`join` takes a set of parameters or a collection and builds a single string, with
each item separated by the specified parameter.
```handlebars
{{join 'Mark' 'Rob' 'Dan' ', '}} // Mark, Rob, Dan
```
You can optionally specify a prefix and suffix:
```handlebars
{{join 'Mark' 'Rob' 'Dan' ', ' prefix='[' suffix=']'}} // [Mark, Rob, Dan]
```
### Justify left and right
`ljust` left-aligns the value in a field of a given width, optionally taking a padding character.
```handlebars
{{ljust 'things' size=20}} // 'things '
{{ljust 'things' size=20 pad='#'}} // 'things##############'
```
`rjust` right-aligns the value in the same manner
```handlebars
{{rjust 'things' size=20}} // ' things'
{{rjust 'things' size=20 pad='#'}} // '##############things'
```
### Lower and upper case
`lower` and `upper` convert the value to all lowercase and all uppercase:
```handlebars
{{lower 'WireMock Cloud'}} // wiremock cloud
{{upper 'WireMock Cloud'}} // WIREMOCK CLOUD
```
### Replace
`replace` replaces all occurrences of the specified substring with the replacement value.
```handlebars
{{replace 'the wrong way' 'wrong' 'right' }} // the right way
```
### Slugify
`slugify` converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace.
```handlebars
{{slugify 'Mock my APIs'}} // mock-my-apis
```
### Split
`split` divides a string into a list of substrings using the given delimiter. The
delimiter is treated as a literal string, not a regular expression.
```handlebars
{{split 'a,b,c' ','}} // ['a', 'b', 'c']
```
The result can be used with other helpers that accept collections, such as `arrayJoin`:
```handlebars
{{arrayJoin '|' (split 'a,b,c' ',')}} // a|b|c
```
### Strip tags
`stripTags` strips all [X]HTML tags.
```handlebars
{{stripTags '
Now make a request to your mock API (substituting `my-mock-api` for your own sub domain name):