๐ฎ 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 โ
- Open Postman โ Environments โ Create New Environment
- Name it:
Partner Services - Development
- Add these variables:
Variable Name | Initial Value | Current Value | Description |
---|---|---|---|
BASE_URL | http://localhost:3000/api/v1 | http://localhost:3000/api/v1 | API base URL |
PARTNER_ID | your_partner_id | your_partner_id | Your partner identifier |
SECRET_KEY | your_secret_key | your_secret_key | HMAC secret key |
REQUEST_ID | (leave empty) | (leave empty) | Auto-generated request ID |
Production Environment โ
For production, create another environment:
Variable Name | Initial Value | Current Value | Description |
---|---|---|---|
BASE_URL | https://partner-services.logistics.com/api/v1 | https://partner-services.logistics.com/api/v1 | Production API URL |
PARTNER_ID | your_prod_partner_id | your_prod_partner_id | Production partner ID |
SECRET_KEY | your_prod_secret_key | your_prod_secret_key | Production secret key |
๐ Step 2: HMAC Pre-Request Script โ
Partner Services HMAC Authentication Script โ
Add this script to your collection's Pre-request Script tab:
/* 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 โ
- Create Collection:
Partner Services API
- Add Description:
# 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
- 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) โ
{
"success": false,
"error": {
"code": "AUTHENTICATION_FAILED",
"message": "Invalid HMAC signature"
}
}
Solutions:
- Verify
PARTNER_ID
andSECRET_KEY
are correct - Check timestamp is within 5-minute window
- Ensure request body format matches exactly
- Enable debug mode to see string-to-sign
โ Invalid Timestamp โ
{
"success": false,
"error": {
"code": "TIMESTAMP_INVALID",
"message": "Request timestamp is too old"
}
}
Solutions:
- Check system clock synchronization
- Regenerate timestamp for each request
- Ensure timestamp is in Unix format (seconds)
โ Partner Not Found โ
{
"success": false,
"error": {
"code": "PARTNER_NOT_FOUND",
"message": "Partner ID not found"
}
}
Solutions:
- Verify
PARTNER_ID
is correct - Check partner account is active
- 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:
{
"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 โ
Environment Setup โ
- Set
PARTNER_ID
andSECRET_KEY
- Select correct environment
- Set
Health Check โ
- Verify API connectivity
- Confirm authentication headers
Partner Data โ
- Test comprehensive data retrieval
- Verify response structure
Availability Check โ
- Test partner availability API
- Verify response format
Charge Calculation โ
- Test charge calculation flow
- Verify pricing structure
End-to-End Flow โ
- Complete shipment assignment workflow
- Test error scenarios
๐ Related Documentation โ
- Authentication Guide - Detailed HMAC implementation
- API Routes Reference - Complete endpoint listing
- API Examples - More request/response examples
- Error Handling - Troubleshooting guide
This Postman setup provides everything you need to test the Partner Services API with automatic HMAC authentication! ๐ฎ