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 Scripts

Advanced Feature
Mock Scripts is an advanced feature that requires JavaScript knowledge. For most use cases, Smart Mock and Mock Expectations are sufficient. You can skip this article if you're just getting started with API mocking.
While Smart Mock and Mock Expectations can handle most scenarios, sometimes you need mock responses that maintain logical relationships between request and response data. Mock Scripts allow you to write JavaScript code to customize mock responses dynamically based on request parameters.
In this article, we'll learn how to use Mock Scripts with the Pet Store API to create intelligent mock responses that maintain data consistency.

1. What Are Mock Scripts?#

Mock Scripts are JavaScript code snippets that run when a mock request is received. They allow you to:
Access request data: Read path parameters, query parameters, headers, and body
Modify response data: Change the Smart Mock-generated response before it's returned
Maintain relationships: Ensure response data matches request parameters (e.g., response ID matches request ID)
Add logic: Implement conditional logic, calculations, and data transformations

When to Use Mock Scripts#

Use Mock Scripts when you need:
Request-response consistency: The response ID should match the ID in the request URL
Logical relationships: Response fields depend on request parameters (e.g., age affects adoption fee)
Dynamic calculations: Compute values based on request data
Conditional responses: Return different data based on request conditions
Note: Mock Scripts only work with Smart Mock. They don't apply to Mock Expectations or response examples.

2. How Mock Scripts Work#

The basic flow is:
1.
Smart Mock generates an initial mock response based on your API spec
2.
Mock Script runs and can access both the request ($$.mockRequest) and the generated response ($$.mockResponse)
3.
Script modifies the response as needed
4.
Final response is returned to the client

Available Objects#

$$.mockRequest: Access request data (parameters, headers, body)
$$.mockResponse: Access and modify the mock response

3. Example 1: Matching Request ID in Response#

Let's start with a simple example: ensuring the pet ID in the response matches the ID in the request URL.

Scenario#

When you request GET /pets/pet_123, the response should include "id": "pet_123"β€”not a random ID generated by Smart Mock.

Step 1: Open the Mock Tab#

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

Step 2: Enable and Write the Script#

1.
Turn on the script toggle
2.
Write the following script:
3.
Click "Save"
image.png

Step 3: Test the Mock#

1.
Use the mock URL with a specific pet ID: GET /pets/pet_1Nv0FGQ9RKHgCVdK
2.
The response will now include "id": "pet_1Nv0FGQ9RKHgCVdK" instead of a random ID
3.
The self link will also use the correct ID
Before Script (Smart Mock only):
{
  "id": "pet_abc123xyz",  // Random ID
  "name": "Luna",
  "species": "DOG",
  ...
}
After Script:
{
  "id": "pet_1Nv0FGQ9RKHgCVdK",  // Matches request ID
  "name": "Luna",
  "species": "DOG",
  "links": {
    "self": "https://api.petstoreapi.com/v1/pets/pet_1Nv0FGQ9RKHgCVdK"
  },
  ...
}

4. Example 2: Dynamic Pagination#

Let's create a more complex example: ensuring pagination metadata matches the request parameters.

Scenario#

For GET /pets?page=2&limit=10, the response should include:
pagination.page = 2 (from request)
pagination.limit = 10 (from request)
pagination.totalPages calculated based on total items

Script#

Result#

When you request GET /pets?page=2&limit=10, the response will have:
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 10,
    "totalItems": 45,
    "totalPages": 5
  },
  "links": {
    "self": "https://api.petstoreapi.com/v1/pets?page=2&limit=10",
    "prev": "https://api.petstoreapi.com/v1/pets?page=1&limit=10",
    "next": "https://api.petstoreapi.com/v1/pets?page=3&limit=10",
    "last": "https://api.petstoreapi.com/v1/pets?page=5&limit=10"
  }
}

5. Example 3: Conditional Logic Based on Request#

You can also use Mock Scripts to return different responses based on request conditions.

Scenario#

For GET /pets/{id}, if the pet ID starts with pet_test_, return a special test pet with predictable data.

Script#

Result#

Request: GET /pets/pet_test_123 β†’ Returns predictable test data
Request: GET /pets/pet_1Nv0FGQ9RKHgCVdK β†’ Returns Smart Mock data with matching ID

6. Common Use Cases#

Accessing Request Data#

Modifying Response Data#


7. Key Takeaways#

Mock Scripts allow you to customize Smart Mock responses with JavaScript
Request-response consistency: Ensure response data matches request parameters
Dynamic logic: Implement calculations, conditional logic, and data transformations
Only works with Smart Mock: Mock Scripts don't apply to Mock Expectations or response examples
Access request data: Use $$.mockRequest to read parameters, headers, and body
Modify response data: Use $$.mockResponse to update the mock response before it's returned
Powerful tool: Enables realistic mock responses that maintain logical relationships

Mock Scripts give you the flexibility to create intelligent mock responses that maintain data consistency and logical relationships. Combined with Smart Mock, Mock Expectations, and Cloud Mock, you have a complete toolkit for API mocking in Apidog.
Ready to move on? Let's review what we've learned in the Chapter Summary.
Modified atΒ 2025-12-29 10:42:25
Previous
Cloud Mock
Next
Chapter Summary
Built with