Skip to content

๐Ÿ“ฎ Postman Setup Guide - Partner Services API โ€‹

๐Ÿ“‹ Overview โ€‹

This guide provides everything you need to set up Postman for testing the Partner Services API, including automatic HMAC authentication using pre-request scripts.

What you'll get:

  • โœ… Automatic HMAC generation for every request
  • โœ… Environment variables for easy configuration
  • โœ… Ready-to-use collection with all endpoints
  • โœ… Debug logging for troubleshooting

๐Ÿ”ง Step 1: Environment Setup โ€‹

Create New Environment โ€‹

  1. Open Postman โ†’ Environments โ†’ Create New Environment
  2. Name it: Partner Services - Development
  3. Add these variables:
Variable NameInitial ValueCurrent ValueDescription
BASE_URLhttp://localhost:3000/api/v1http://localhost:3000/api/v1API base URL
PARTNER_IDyour_partner_idyour_partner_idYour partner identifier
SECRET_KEYyour_secret_keyyour_secret_keyHMAC secret key
REQUEST_ID(leave empty)(leave empty)Auto-generated request ID

Production Environment โ€‹

For production, create another environment:

Variable NameInitial ValueCurrent ValueDescription
BASE_URLhttps://partner-services.logistics.com/api/v1https://partner-services.logistics.com/api/v1Production API URL
PARTNER_IDyour_prod_partner_idyour_prod_partner_idProduction partner ID
SECRET_KEYyour_prod_secret_keyyour_prod_secret_keyProduction secret key

๐Ÿ” Step 2: HMAC Pre-Request Script โ€‹

Partner Services HMAC Authentication Script โ€‹

Add this script to your collection's Pre-request Script tab:

javascript
/* eslint-disable no-undef */
/**
 * ๐Ÿ”ง POSTMAN SERVICE AUTHENTICATION SCRIPT - WORKING VERSION
 *
 * Use this script for ALL Service-level API endpoints that require service authentication.
 *
 * SETUP:
 * 1. Copy this script into your Postman request's "Pre-request Script" tab
 * 2. Set environment variables in Postman:
 *    - HMAC_SECRET: hmac_super_secret_key_2024_partner_services
 *    - API_SECRET_SALT: api_secret_salt_2024_partner_services
 *    - SERVICE_ID: TESTING_1 (or your actual service ID)
 *    - BASE_URL: http://localhost:3000/api/v1
 *
 * AUTHENTICATION: HMAC SHA-256 with service-specific secret generation
 */

// Environment variables from Postman
const HMAC_SECRET =
  pm.environment.get("HMAC_SECRET") || pm.variables.get("HMAC_SECRET");
const API_SECRET_SALT =
  pm.environment.get("API_SECRET_SALT") || pm.variables.get("API_SECRET_SALT");
const SERVICE_ID =
  pm.environment.get("SERVICE_ID") || pm.variables.get("SERVICE_ID");

// Validation
if (!HMAC_SECRET) {
  throw new Error("HMAC_SECRET environment variable is required");
}
if (!API_SECRET_SALT) {
  throw new Error("API_SECRET_SALT environment variable is required");
}
if (!SERVICE_ID) {
  throw new Error("SERVICE_ID environment variable is required");
}

console.log("๐Ÿ” Generating Service HMAC Authentication Headers...");
console.log("Service ID:", SERVICE_ID);

/**
 * Generate service-specific secret (matching middleware implementation)
 */
function generateServiceSecret(serviceId) {
  const data = `${serviceId}:${API_SECRET_SALT}`;
  console.log("Secret generation data:", data);
  const secret = CryptoJS.HmacSHA256(data, HMAC_SECRET).toString(
    CryptoJS.enc.Hex
  );
  console.log("Generated service secret:", secret);
  return secret;
}

/**
 * Generate HMAC signature for request
 */
function generateSignature(secret, method, url, timestamp, requestBody) {
  const message = `${method}${url}${timestamp}${requestBody}`;
  console.log("Signature message:", `"${message}"`);
  const signature = CryptoJS.HmacSHA256(message, secret).toString(
    CryptoJS.enc.Hex
  );
  console.log("Generated signature:", signature);
  return signature;
}

// Get request details
const method = pm.request.method;

// Extract URL path properly
let fullUrl = pm.request.url.toString();
console.log("Original full URL:", fullUrl);

// Resolve {{baseUrl}} and other variables if present
if (fullUrl.includes("{{")) {
  fullUrl = fullUrl.replace(/{{(\w+)}}/g, (_, k) => pm.variables.get(k) || "");
  console.log("URL after variable resolution:", fullUrl);
}

// Extract path from the full URL
let url = "/";
try {
  const parsedUrl = new URL(fullUrl);
  url = parsedUrl.pathname;

  // Add query parameters if they exist
  if (parsedUrl.search) {
    url += parsedUrl.search;
  }
} catch (err) {
  console.error("โŒ Failed to parse path from URL:", err);
  // Fallback to Postman's getPath method
  url = pm.request.url.getPath();
  if (pm.request.url.query && pm.request.url.query.count() > 0) {
    const queryString = pm.request.url.getQueryString();
    if (queryString) {
      url += "?" + queryString;
    }
  }
}

console.log("Extracted URL path:", url);

const timestamp = Math.floor(Date.now() / 1000).toString();

// Get request body (if any)
let requestBody = "";
if (pm.request.body && pm.request.body.mode) {
  if (pm.request.body.mode === "raw") {
    const rawBody = pm.request.body.raw;
    if (rawBody && rawBody.trim() !== "") {
      try {
        // Ensure consistent JSON formatting
        const parsed = JSON.parse(rawBody);
        requestBody = JSON.stringify(parsed);
      } catch (error) {
        // Use raw body if JSON parsing fails
        requestBody = rawBody;
        console.log(
          "Warning: Could not parse request body as JSON, using raw body",
          error
        );
      }
    }
  }
}

// Generate authentication components
const serviceSecret = generateServiceSecret(SERVICE_ID);
const signature = generateSignature(
  serviceSecret,
  method,
  url,
  timestamp,
  requestBody
);

// Remove existing auth headers first to avoid duplicates
pm.request.headers.remove("x-service-id");
pm.request.headers.remove("x-timestamp");
pm.request.headers.remove("x-signature");

// Set authentication headers
pm.request.headers.add({
  key: "x-service-id",
  value: SERVICE_ID,
});

pm.request.headers.add({
  key: "x-timestamp",
  value: timestamp,
});

pm.request.headers.add({
  key: "x-signature",
  value: signature,
});

// pm.request.headers.add({
//     key: 'x-partner-id',
//     value: 'test-123'
// });

// Debug information
console.log("=== DETAILED DEBUG INFO ===");
console.log("Method:", method);
console.log("Full URL:", fullUrl);
console.log("Extracted Path:", url);
console.log("Timestamp:", timestamp);
console.log("Request Body:", requestBody || "(empty)");
console.log("Service Secret:", serviceSecret);
console.log("Final Signature:", signature);
console.log("========================");

// Validation warnings
if (url === "/pincodes/search") {
  console.log("๐Ÿšจ CRITICAL ERROR: URL path is '/pincodes/search'");
  console.log("This means your Postman URL is probably:");
  console.log("โŒ http://localhost:3000/pincodes/search");
  console.log("");
  console.log("Change it to:");
  console.log("โœ… http://localhost:3000/api/v1/pincodes/search");
  console.log("");
  console.log("The endpoint /pincodes/search does NOT exist on the server!");
  console.log("All endpoints are under /api/v1/ prefix.");
}

if (!url.startsWith("/api/v1/")) {
  console.log("โš ๏ธ WARNING: URL does not start with /api/v1/");
  console.log("Current URL path:", url);
  console.log("Expected URL path should start with: /api/v1/");
}

console.log("โœ… Service HMAC headers generated successfully!");
console.log("Headers added: x-service-id, x-timestamp, x-signature");

/**
 * CRITICAL SETUP INSTRUCTIONS:
 *
 * 1. Postman Environment Variables:
 *    HMAC_SECRET = hmac_super_secret_key_2024_partner_services
 *    API_SECRET_SALT = api_secret_salt_2024_partner_services
 *    SERVICE_ID = TESTING_1
 *
 * 2. Request URL MUST be complete path:
 *    โœ… CORRECT: http://localhost:3000/api/v1/pincodes/search
 *    โŒ WRONG:   http://localhost:3000/pincodes/search
 *
 * 3. The server does NOT have routes at /pincodes/search
 *    All routes are under /api/v1/ prefix
 */

๐Ÿ“ Step 3: Collection Setup โ€‹

Create New Collection โ€‹

  1. Create Collection: Partner Services API
  2. Add Description:
markdown
# Partner Services API Collection

Complete collection for testing Partner Services integration.

## Authentication

This collection uses HMAC SHA-256 authentication. Make sure to:

1. Set up environment variables (PARTNER_ID, SECRET_KEY)
2. Use the pre-request script for automatic signature generation

## Base URL

Development: http://localhost:3000/api/v1
Production: https://partner-services.logistics.com/api/v1
  1. Add Pre-request Script: Copy the HMAC script above to the collection's Pre-request Script tab

Folder Structure โ€‹

Organize your requests into folders:

๐Ÿ“ Partner Services API
โ”œโ”€โ”€ ๐Ÿ“ Health & System
โ”‚   โ”œโ”€โ”€ GET Health Check
โ”‚   โ””โ”€โ”€ GET API Information
โ”œโ”€โ”€ ๐Ÿ“ Authentication Tests
โ”‚   โ”œโ”€โ”€ GET Test Authentication
โ”‚   โ””โ”€โ”€ POST Authentication Debug
โ”œโ”€โ”€ ๐Ÿ“ Partner Data
โ”‚   โ”œโ”€โ”€ GET Comprehensive Partner Data
โ”‚   โ”œโ”€โ”€ GET Partner Zones
โ”‚   โ”œโ”€โ”€ GET Partner Services
โ”‚   โ”œโ”€โ”€ GET Partner Charges
โ”‚   โ””โ”€โ”€ GET Partner Discounts
โ”œโ”€โ”€ ๐Ÿ“ Geographical Data
โ”‚   โ”œโ”€โ”€ GET All States
โ”‚   โ”œโ”€โ”€ GET Cities by State
โ”‚   โ”œโ”€โ”€ GET Areas by City
โ”‚   โ””โ”€โ”€ GET Pincode Details
โ”œโ”€โ”€ ๐Ÿ“ Zone Management
โ”‚   โ”œโ”€โ”€ GET All Zones
โ”‚   โ”œโ”€โ”€ POST Create Zone
โ”‚   โ”œโ”€โ”€ PUT Update Zone
โ”‚   โ””โ”€โ”€ DELETE Remove Zone
โ”œโ”€โ”€ ๐Ÿ“ Shipment Operations
โ”‚   โ”œโ”€โ”€ POST Check Availability
โ”‚   โ”œโ”€โ”€ POST Calculate Charges
โ”‚   โ””โ”€โ”€ POST Assign Shipment
โ””โ”€โ”€ ๐Ÿ“ Package & Service Management
    โ”œโ”€โ”€ GET Service Types
    โ”œโ”€โ”€ GET Package Charges
    โ””โ”€โ”€ GET Customer Charges

๐Ÿงช Step 4: Sample Requests โ€‹

1. Health Check โ€‹

Method: GET
URL: {{BASE_URL}}/health
Headers: (Auto-generated by script)

2. Partner Data โ€‹

Method: GET
URL: {{BASE_URL}}/partners/comprehensive-data
Headers: (Auto-generated by script)
Query Params:
- format: standard
- includeStatistics: true

3. Calculate Charges โ€‹

Method: POST
URL: {{BASE_URL}}/shipments/calculate-charges
Headers: (Auto-generated by script)
Body (JSON):
{
  "partnerId": "{{PARTNER_ID}}",
  "pickupPincode": "110001",
  "deliveryPincode": "400001",
  "weight": 2500,
  "shipmentType": "B2C",
  "paymentType": "COD",
  "declaredValue": 3500
}

4. Check Availability โ€‹

Method: POST
URL: {{BASE_URL}}/partners/availability/check
Headers: (Auto-generated by script)
Body (JSON):
{
  "pickupPincode": "110001",
  "deliveryPincode": "400001",
  "weight": 2500,
  "shipmentType": "B2C",
  "paymentType": "COD",
  "serviceRequirements": ["PICKUP", "DELIVERY", "COD"]
}

๐Ÿ› Step 5: Debugging & Troubleshooting โ€‹

Enable Debug Mode โ€‹

Add this environment variable to see detailed HMAC information:

  • Variable: DEBUG_HMAC
  • Value: true

Common Issues & Solutions โ€‹

โŒ Authentication Failed (401) โ€‹

json
{
  "success": false,
  "error": {
    "code": "AUTHENTICATION_FAILED",
    "message": "Invalid HMAC signature"
  }
}

Solutions:

  1. Verify PARTNER_ID and SECRET_KEY are correct
  2. Check timestamp is within 5-minute window
  3. Ensure request body format matches exactly
  4. Enable debug mode to see string-to-sign

โŒ Invalid Timestamp โ€‹

json
{
  "success": false,
  "error": {
    "code": "TIMESTAMP_INVALID",
    "message": "Request timestamp is too old"
  }
}

Solutions:

  1. Check system clock synchronization
  2. Regenerate timestamp for each request
  3. Ensure timestamp is in Unix format (seconds)

โŒ Partner Not Found โ€‹

json
{
  "success": false,
  "error": {
    "code": "PARTNER_NOT_FOUND",
    "message": "Partner ID not found"
  }
}

Solutions:

  1. Verify PARTNER_ID is correct
  2. Check partner account is active
  3. Ensure API access is enabled for partner

Debug Console Output โ€‹

When the script runs successfully, you'll see:

๐Ÿ” Partner Services HMAC Authentication {
  method: "POST",
  path: "/api/v1/shipments/calculate-charges",
  timestamp: 1642752000,
  partnerId: "partner_001",
  bodyLength: 156,
  stringToSign: "POST\\n/api/v1/shipments/calculate-charges\\n{...}\\n1642752000",
  signature: "a1b2c3d4e5f6...",
  requestId: "req_1642752000_xyz123"
}
โœ… HMAC authentication headers set successfully

๐Ÿ“ฆ Step 6: Import Ready-Made Collection โ€‹

Quick Import JSON โ€‹

Save this as partner-services-collection.json and import into Postman:

json
{
  "info": {
    "name": "Partner Services API",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    "description": "Complete Partner Services API collection with HMAC authentication"
  },
  "auth": {
    "type": "noauth"
  },
  "event": [
    {
      "listen": "prerequest",
      "script": {
        "type": "text/javascript",
        "exec": [
          "// Partner Services HMAC Authentication Script",
          "// Copy the full script from Step 2 above"
        ]
      }
    }
  ],
  "variable": [
    {
      "key": "BASE_URL",
      "value": "http://localhost:3000/api/v1"
    }
  ],
  "item": [
    {
      "name": "Health Check",
      "request": {
        "method": "GET",
        "header": [],
        "url": {
          "raw": "{{BASE_URL}}/health",
          "host": ["{{BASE_URL}}"],
          "path": ["health"]
        }
      }
    },
    {
      "name": "Get Partner Data",
      "request": {
        "method": "GET",
        "header": [],
        "url": {
          "raw": "{{BASE_URL}}/partners/comprehensive-data?format=standard",
          "host": ["{{BASE_URL}}"],
          "path": ["partners", "comprehensive-data"],
          "query": [
            {
              "key": "format",
              "value": "standard"
            }
          ]
        }
      }
    },
    {
      "name": "Calculate Charges",
      "request": {
        "method": "POST",
        "header": [],
        "body": {
          "mode": "raw",
          "raw": "{\n  \"partnerId\": \"{{PARTNER_ID}}\",\n  \"pickupPincode\": \"110001\",\n  \"deliveryPincode\": \"400001\",\n  \"weight\": 2500,\n  \"shipmentType\": \"B2C\",\n  \"paymentType\": \"COD\",\n  \"declaredValue\": 3500\n}",
          "options": {
            "raw": {
              "language": "json"
            }
          }
        },
        "url": {
          "raw": "{{BASE_URL}}/shipments/calculate-charges",
          "host": ["{{BASE_URL}}"],
          "path": ["shipments", "calculate-charges"]
        }
      }
    }
  ]
}

๐Ÿ”— Step 7: Testing Workflow โ€‹

Complete Testing Sequence โ€‹

  1. Environment Setup โœ“

    • Set PARTNER_ID and SECRET_KEY
    • Select correct environment
  2. Health Check โœ“

    • Verify API connectivity
    • Confirm authentication headers
  3. Partner Data โœ“

    • Test comprehensive data retrieval
    • Verify response structure
  4. Availability Check โœ“

    • Test partner availability API
    • Verify response format
  5. Charge Calculation โœ“

    • Test charge calculation flow
    • Verify pricing structure
  6. End-to-End Flow โœ“

    • Complete shipment assignment workflow
    • Test error scenarios


This Postman setup provides everything you need to test the Partner Services API with automatic HMAC authentication! ๐Ÿ“ฎ

Released under the MIT License.