API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Working with 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. Working with APIs

Handling API Signatures

Advanced Feature
Handling API Signatures is an advanced feature that requires JavaScript knowledge and understanding of cryptographic concepts. Most APIs use simpler authentication methods like Bearer tokens. You can skip this article if you're just getting started with APIs.
Some APIs require signature verification to ensure the integrity and authenticity of requests. An API signature is a cryptographic hash generated from request parameters using a secret key. The server verifies the signature to ensure the request hasn't been tampered with and comes from an authorized source.
In this article, we'll learn how to handle API signatures in Apidog using preprocessor scripts and public scripts to automatically generate and add signatures to your requests.

1. What Is an API Signature?#

An API signature is a cryptographic value generated from your request parameters and a secret key. It serves several purposes:
Integrity verification: Ensures the request hasn't been modified during transmission
Authentication: Proves the request comes from an authorized source
Security: Prevents request tampering and replay attacks

How Signatures Work#

A typical signature generation process:
1.
Collect parameters: Gather all request parameters (query params, body params, etc.)
2.
Sort and concatenate: Sort parameters by name and concatenate them in a specific format
3.
Add secret key: Use your secret key with a cryptographic algorithm (like HMAC-SHA256)
4.
Generate hash: Create a signature hash from the concatenated string
5.
Add to request: Include the signature in the request header or as a parameter
The server performs the same calculation and compares the result. If they match, the request is valid.

2. Why Use Scripts for Signatures?#

Manually calculating and adding signatures for every request would be:
Time-consuming: You'd need to recalculate for each request
Error-prone: Easy to make mistakes in the calculation
Inflexible: Hard to update if the signature algorithm changes
Apidog allows you to automate this process using preprocessor scripts that run before each request is sent. You can create a public script that implements the signature logic once and reuse it across multiple endpoints.

3. Real-World Example: HMAC-SHA256 Signature#

Many real-world APIs use HMAC-SHA256 (Hash-based Message Authentication Code with SHA-256) for signature verification. This is a widely adopted standard used by services like Stripe (for webhooks), GitHub (for webhook signatures), and many cloud service providers.

How HMAC-SHA256 Works#

The HMAC-SHA256 signature algorithm follows these steps:
1.
Collect parameters: Gather all request parameters (query params, body params, timestamp, etc.)
2.
Sort parameters: Sort parameter names alphabetically (ASCII order)
3.
Build string to sign: Concatenate parameters in key=value format, joined with &
4.
Add timestamp: Include a timestamp to prevent replay attacks
5.
Generate HMAC: Use HMAC-SHA256 algorithm with your secret key to generate the signature
6.
Add to request: Include the signature in the request header or as a parameter

Example Calculation#

Let's say we have a request with the following parameters:
action: create
resource: pet
timestamp: 1633046400
api_key: your_api_key_12345
Step 1: Sort parameters alphabetically: action, api_key, resource, timestamp
Step 2: Build string to sign: action=create&api_key=your_api_key_12345&resource=pet&timestamp=1633046400
Step 3: Generate HMAC-SHA256 with secret key your_secret_key:
HMAC-SHA256("action=create&api_key=your_api_key_12345&resource=pet&timestamp=1633046400", "your_secret_key")
Step 4: The signature is added to the request as a query parameter or in the Authorization header.

4. Step-by-Step Guide#

Now let's implement signature generation in Apidog. We'll create a public script that automatically generates and adds signatures to your requests.

Step 1: Set Up Environment Variables#

First, we need to store the secret key securely:
1.
Open Environment Management (click the ≑ icon in the top-right corner).
2.
Select your environment (e.g., "Production" or "Sandbox").
3.
Add a variable:
Variable Name: SECRET_KEY
Initial Value: (leave empty or use a placeholder)
Current Value: Your API secret key (provided by the API provider)
4.
Click "Save".
Security Note:
Never hardcode secret keys in your scripts or API specifications.
Store sensitive keys in Current Value rather than Initial Value, as Current Value is not synchronized across team members and is more secure.
Always use environment variables to store sensitive information like API keys and secrets.

Step 2: Create a Public Script#

Now let's create a reusable public script that generates HMAC-SHA256 signatures:
1.
In Apidog, go to Settings β†’ Public Scripts.
2.
Click "New Public Script" or the "+" button.
3.
Enter a name for your script (e.g., "HMAC-SHA256 Signature Generator").
4.
Enter the signature generation code:
5.
Click "Save" to save the public script.
image.png

Step 3: Reference the Public Script in Your Endpoint#

Now that we've created the public script, we need to reference it in the endpoints that require signatures:
1.
Open any endpoint that requires signature verification (e.g., POST /pets).
2.
Switch to the "Run" tab.
3.
Scroll down to the Pre Processors section.
4.
Click "Add PreProcessor" and select "Public Script".
5.
Select the public script you just created (e.g., "HMAC-SHA256 Signature Generator").
image.png
6.
The public script will now run automatically before each request is sent, generating and adding the signature.

5. How It Works#

When you send a request with the signature script enabled:
1.
Pre Processors run: The public script executes before the request is sent.
2.
Parameters collected: The script gathers all query parameters and body parameters.
3.
Timestamp added: If not present, a Unix timestamp is automatically added to prevent replay attacks.
4.
Parameters sorted: Parameter names are sorted alphabetically.
5.
String built: Parameters are concatenated as key=value pairs, joined with &.
6.
Signature generated: HMAC-SHA256 algorithm is applied using your secret key.
7.
Signature added: The signature is automatically added to the request as a query parameter.
8.
Request sent: The request is sent with the signature included.
You can verify this by checking the "Actual Request" tab after sending a request. You should see the signature parameter included in the query string.

6. Testing Your Signature#

To verify that your signature is working correctly:
1.
Set up your endpoint: Create an endpoint that requires signature verification (e.g., POST /api/resource) with query parameters or body parameters.
2.
Add the public script: Reference the "HMAC-SHA256 Signature Generator" script in the Pre Processors.
3.
Send the request: Click "Send" to execute the request.
4.
Check the actual request: Switch to the "Actual Request" tab. You should see:
timestamp parameter added automatically (if not already present)
signature parameter added automatically with the HMAC-SHA256 hash
5.
Verify the response: If the signature is correct, you'll receive a successful response. If you get a signature verification error:
Verify that SECRET_KEY environment variable is set correctly
Check the console logs to see the "String to sign" and "Generated signature" values
Ensure parameter sorting matches the API's requirements
Verify that the HMAC-SHA256 algorithm is correct
Check that the timestamp is within the API's accepted time window

7. Key Takeaways#

API signatures verify request integrity and authenticity using cryptographic hashes.
HMAC-SHA256 is a widely used standard for API signatures, used by services like Stripe and GitHub.
Public scripts allow you to create reusable signature generation logic.
Pre Processors run before requests are sent, making them perfect for adding signatures automatically.
Environment variables should be used to store secret keys securely.
Signature algorithms vary by APIβ€”always follow the API provider's specific requirements.
Test thoroughly to ensure your signature matches the API's expected format.

By automating signature generation with scripts, you can seamlessly work with APIs that require signature verification without manually calculating signatures for each request. This makes your API testing workflow more efficient and less error-prone.
Continue with β†’ Introduction to Scripts
Modified atΒ 2025-12-25 09:40:03
Previous
Handling Authentication
Next
Introduction to Scripts
Built with