API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Mocking APIs
  • Introduction
  • Table of Contents
  • API Academy
    • Get Started
      • What is an API?
      • How Does an API Work?
      • How to Call an API?
      • How to Read an API Documentation?
      • Chapter Summary
      • Get realtime weather
    • API Fundamentals
      • API Funtamentals: Overview
      • Method & Path
      • Parameters
      • Request Body
      • Responses
      • API Specification & OAS
      • Chapter Summary
    • Working with APIs
      • Working with APIs: Overview
      • Making Requests from Spec
      • Environments and Variables
      • Chaining Multiple Endpoints
      • Handling Authentication
      • Handling API Signatures
      • Introduction to Scripts
      • Chapter Summary
    • Mocking APIs
      • Mocking APIs: Overview
      • Smart Mock
      • Mock Expectations
      • Cloud Mock
      • Mock Scripts
      • Chapter Summary
    • Designing APIs
      • Designing APIs: Overview
      • Introduction to API Design
      • Creating Your First API Project
      • Analyzing Requirements and Planning Your API
      • Designing Data Models
      • Designing Endpoints
      • Using Components and Reusability
      • Setting Up Authentication
      • API Design Guidelines
      • Chapter Summary
    • Developing APIs
      • Developing APIs: Overview
      • Setup: Install Your AI Coding Assistant
      • Quick Start: From Spec to Running API in 30 Minutes
      • Understanding the Generated Code
      • Testing Your API with Apidog
      • Deployment: Put Your API Online
      • Chapter Summary
    • Testing APIs
      • Testing APIs: Overview
      • Getting Started: Your First Test Scenario
      • Integration Testing and Data Passing
      • Dynamic Values
      • Assertions and Validations
      • Flow Control: If, For, ForEach
      • Data-Driven Testing
      • Performance Testing
      • Test Reports and Analysis
      • CI/CD Integration
      • Scheduled Tasks and Automation
      • Advanced Testing Strategies
      • Chapter Summary
    • API Documentations
      • API Documentations: Overview
      • Publishing Your First API Doc
      • Customizing Documentation Appearance
      • Interactive Features for Consumers
      • Advanced Publishing Settings
      • Managing API Versions
      • Chapter Summary
    • Advanced API Technologies
      • API Technologies: Overview
      • GraphQL
      • gRPC
      • WebSocket
      • Socket.IO
      • Server-Sent Events (SSE)
      • SOAP
      • Chapter Summary
    • API Lifecycle
      • API Lifecycle: Overview
      • Stages of the API Lifecycle
      • API Governance
      • API Security Best Practices
      • Monitoring and Analytics
      • API Versioning Strategies
      • The Future of APIs
      • Chapter Summary
    • API Security
      • API Security: Overview
      • API Security Fundamentals
      • Authentication vs Authorization
      • Understanding OAuth 2.0 and OpenID Connect
      • JSON Web Tokens (JWT)
      • OWASP API Security Top 10
      • Encryption and HTTPS
      • Chapter Summary
    • API Tools
      • API Tools: Overview
      • The Evolution of API Tools
      • API Clients
      • Command Line Tools (cURL, HTTPie)
      • API Design and Documentation Tools
      • API Mocking Tools
      • API Testing Tools
      • All-in-One API Platforms
      • Chapter Summary
    • API Gateway
      • API Gateway: Overview
      • What is an API Gateway?
      • Key Features of API Gateways
      • API Gateway vs Load Balancer vs Service Mesh
      • Popular API Gateway Solutions
      • The BFF (Backend for Frontend) Pattern
      • Chapter Summary
  • Modern Pet Store
    • Pet
      • Get Pet
      • Update Pet
      • Delete Pet
      • Create Pet
      • List Pets
      • Upload Pet Image
    • User
      • Update User
      • Get User
      • Delete User
      • Login
      • Logout
      • Create User
    • Store
      • List Inventory
      • Create Order
      • Get Order
      • Delete Order
      • Callback Example
      • Pay for an Order
    • Payments
      • Pay Order
    • Chat
      • Create Chat Completion
    • Webhooks
      • Pet Adopted Event
      • New Pet Available Event
  • Schemas
    • Pet
    • Category
    • User
    • ApiResponse
    • OrderPayment
    • Tag
    • Order
    • Links-Order
    • PetCollection
    • Bank Card
    • Bank Account
    • Links
    • Error
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Mocking APIs

Mock Expectations

While Smart Mock automatically generates data based on your API specification, sometimes you need more control. Mock Expectations allow you to define custom mock responses with specific conditions, giving you full control over what the mock server returns.
In this article, we'll learn how to create mock expectations for the Pet Store API, including fixed responses, conditional responses, and dynamic responses.

1. What Are Mock Expectations?#

Mock Expectations are custom mock responses that you define for specific scenarios. Unlike Smart Mock (which generates data automatically), mock expectations let you:
Return fixed data that never changes
Return different responses based on request parameters
Return dynamic data using templates and expressions
Mock expectations have the highest priorityβ€”if a request matches an expectation's conditions, that expectation's response will be returned instead of Smart Mock.

2. When to Use Mock Expectations#

Use mock expectations when you need:
Specific test scenarios: Test how your application handles specific responses (success, errors, edge cases)
Conditional responses: Return different data based on request parameters (e.g., different responses for different IDs)
Fixed responses: Always return the same data for consistency
Error simulation: Simulate error responses (404, 500, etc.) for testing

3. Creating a Fixed Mock Expectation#

Let's start with the simplest case: creating a mock expectation that always returns the same data.

Example: Always Return a Specific Pet#

Suppose you want the GET /pets/{id} endpoint to always return a specific pet when called:

Step 1: Open the Mock Tab#

1.
Open the GET /pets/{id} endpoint in your Pet Store API
2.
Switch to the "Mock" tab
image.png

Step 2: Create a New Expectation#

1.
Click "New expectation"
2.
Enter a name for the expectation (e.g., "Fixed Pet Response")
3.
Leave the Conditions section empty (no conditions = always matches)
4.
In the Response section, enter the JSON data you want to return:
{
  "id": "pet_123",
  "name": "Luna",
  "species": "DOG",
  "breed": "Golden Retriever",
  "ageMonths": 24,
  "status": "AVAILABLE",
  "adoptionFee": 150.00
}
5.
Click "Save"
image.png

Step 3: Use the Mock URL#

1.
Copy the mock URL provided for this expectation
2.
Use it in your browser or application
3.
The mock server will always return the exact data you specified

4. Creating Conditional Mock Expectations#

The real power of mock expectations is conditional responsesβ€”returning different data based on request parameters.

Example: Different Responses for Different Pet IDs#

Let's create expectations that return different pets based on the id path parameter:

Step 1: Create Expectation for ID "pet_123"#

1.
Click "New expectation"
2.
Enter name: "Pet 123 - Luna"
3.
In Conditions, add a condition:
Parameter Type: Path Parameter
Parameter Name: id
Value: pet_123
4.
In Response, enter:
{
  "id": "pet_123",
  "name": "Luna",
  "species": "DOG",
  "breed": "Golden Retriever",
  "status": "AVAILABLE"
}
5.
Click "Save"

Step 2: Create Expectation for ID "pet_456"#

1.
Click "New expectation" again
2.
Enter name: "Pet 456 - Max"
3.
In Conditions, add:
Parameter Type: Path Parameter
Parameter Name: id
Value: pet_456
4.
In Response, enter:
{
  "id": "pet_456",
  "name": "Max",
  "species": "CAT",
  "breed": "Persian",
  "status": "PENDING"
}
5.
Click "Save"

Step 3: Test the Conditional Responses#

1.
Use the mock URL with id=pet_123 β†’ Returns Luna's data
2.
Use the mock URL with id=pet_456 β†’ Returns Max's data
3.
Use the mock URL with any other ID β†’ Falls back to Smart Mock (if no conditions match)
image.png

How Matching Works#

Mock expectations are checked from top to bottom
The first matching expectation is used
If no conditions match, Apidog falls back to Smart Mock or response examples

5. Supported Condition Types#

You can create conditions based on:
Query parameters: ?status=AVAILABLE
Path parameters: /pets/{id} where id=pet_123
Header parameters: Custom headers like X-User-Id
Cookie parameters: Cookie values
Body parameters: JSON body fields (JSON only)
Example: Create an expectation that returns different responses based on a query parameter:
Condition: Query parameter status equals "AVAILABLE"
Response: Returns only available pets

6. Creating Dynamic Mock Expectations#

You can also create expectations that generate dynamic data using Faker.js and Nunjucks templates.

Example: Generate a List of Pets#

Let's create an expectation that generates a dynamic list of pets:
1.
Click "New expectation"
2.
Enter name: "Dynamic Pet List"
3.
Leave conditions empty (or add your conditions)
4.
In Response, use a template:
{
  "pets": [
    {% for i in range(0, 5) %}
    {% if i>0 %},{% endif %}
    {
      "id": "pet_{{i}}",
      "name": "{{$person.firstName}}",
      "species": "{{$helpers.arrayElement(['DOG','CAT'])}}",
      "ageMonths": {{$number.int(min=1,max=120)}}
    }
    {% endfor %}
  ],
  "total": 5
}
This generates:
An array of 5 pet objects
Each with a unique ID (pet_0, pet_1, etc.)
Random names, species, and ages

Template Syntax#

{{$...}} β†’ Faker.js expressions for random data
{% for ... %} β†’ Nunjucks loops
{% if ... %} β†’ Nunjucks conditionals

7. Advanced Features#

Mock expectations support additional features:

Custom Response Headers#

Add custom headers to simulate authentication, pagination, etc.:
1.
In the expectation, go to the Headers section
2.
Add headers like X-Total-Count: 100 or Authorization: Bearer token123
image.png

HTTP Status Codes#

Simulate different HTTP status codes:
1.
In the expectation, click "More"
2.
Set HTTP Status Code to 404, 500, etc. (default is 200)

Response Delay#

Simulate slow API responses:
1.
In the "More" tab
2.
Set Response Delay (in milliseconds)
3.
Useful for testing how your application handles slow responses
image.png

Enable/Disable Expectations#

You can toggle expectations on/off for different environments (Local mock, Cloud mock) without deleting them.

8. Key Takeaways#

Mock Expectations give you full control over mock responses
Fixed expectations always return the same data
Conditional expectations return different data based on request parameters
Dynamic expectations use templates to generate variable data
Highest priority: Mock expectations override Smart Mock
Multiple conditions: You can combine query, path, header, and body parameters
Advanced features: Custom headers, status codes, and delays for realistic testing

Mock Expectations provide the flexibility to create sophisticated mock scenarios for testing and development. In the next article, we'll learn about Cloud Mockβ€”how to deploy mock servers in the cloud for team-wide access.
Continue with β†’ Cloud Mock
Modified atΒ 2025-12-25 09:44:49
Previous
Smart Mock
Next
Cloud Mock
Built with