Complete Express API Testing Guide with Step-by-Step Procedures

Initial Setup

Before we begin testing our API endpoints, we need to set up our testing environment properly. This setup will ensure we can test efficiently and systematically.

Setting Up Postman

Let's create a complete testing environment in Postman that we'll use throughout our testing:

  1. Create a New Collection
    • Open Postman and click "Create Collection"
    • Name it "Express Authentication API"
    • Click "Create"
  2. Set Up Environment Variables
    • Click "Environments" in the sidebar
    • Click "Create Environment"
    • Name it "Local Development"
    • Add these variables:
      baseUrl: http://localhost:8000
      xsrfToken: [leave empty initially]
      authToken: [leave empty initially]
    • Save the environment
  3. Create Collection Pre-request Script
    • Select your collection
    • Go to the "Pre-request Scripts" tab
    • Add this script to automatically fetch CSRF token:
      pm.sendRequest({
          url: pm.environment.get("baseUrl") + "/api/csrf/restore",
          method: 'GET'
      }, function (err, res) {
          if (!err) {
              pm.environment.set("xsrfToken", res.cookies.get("XSRF-TOKEN"));
          }
      });

Setting Up for cURL Testing

For cURL testing, we'll need to store our CSRF token for repeated use. Let's create a script to help with this:

#!/bin/bash
# Save as get-csrf.sh

# Get CSRF token and save it
TOKEN=$(curl -s -X GET http://localhost:8000/api/csrf/restore \
  --cookie-jar cookies.txt \
  | grep -o '"XSRF-Token":"[^"]*' \
  | cut -d'"' -f4)

echo "CSRF Token: $TOKEN"
echo "Token saved to cookies.txt"

Make the script executable:

chmod +x get-csrf.sh

Testing User Registration (POST /api/users)

Postman Step-by-Step Procedure

  1. Create New Request
    • In your collection, click "Add Request"
    • Name it "User Registration"
    • Set method to POST
    • Set URL to: {{baseUrl}}/api/users
  2. Configure Headers
    • Add Content-Type: application/json
    • Add XSRF-TOKEN: {{xsrfToken}}
  3. Configure Body
    • Select "raw" and "JSON"
    • Add registration data:
      {
          "firstName": "John",
          "lastName": "Smith",
          "email": "john.smith@gmail.com",
          "username": "JohnSmith",
          "password": "secret password"
      }
  4. Add Tests
    • Click the "Tests" tab
    • Add test script:
      pm.test("Status code is 201", function () {
          pm.response.to.have.status(201);
      });
      
      pm.test("User is created successfully", function () {
          const responseJson = pm.response.json();
          pm.expect(responseJson.user).to.have.property('id');
          pm.expect(responseJson.user.username).to.eql('JohnSmith');
      });
      
      if (pm.response.code === 201) {
          pm.environment.set("authToken", pm.response.headers.get("Set-Cookie"));
      }

cURL Step-by-Step Procedure

  1. Get CSRF Token
    ./get-csrf.sh
  2. Save Registration Data
    cat > register.json << EOF
    {
        "firstName": "John",
        "lastName": "Smith",
        "email": "john.smith@gmail.com",
        "username": "JohnSmith",
        "password": "secret password"
    }
    EOF
  3. Send Registration Request
    curl -X POST http://localhost:8000/api/users \
      -H "Content-Type: application/json" \
      -H "XSRF-TOKEN: $TOKEN" \
      -b cookies.txt \
      -d @register.json

Testing Validation Rules

Test each validation rule using both Postman and cURL:

Invalid Email Format

Postman:

  1. Modify the request body to use invalid email:
    {
        "firstName": "John",
        "lastName": "Smith",
        "email": "invalid-email",
        "username": "JohnSmith",
        "password": "secret password"
    }
  2. Send request and verify 400 status code

cURL:

curl -X POST http://localhost:8000/api/users \
  -H "Content-Type: application/json" \
  -H "XSRF-TOKEN: $TOKEN" \
  -b cookies.txt \
  -d '{"firstName":"John","lastName":"Smith","email":"invalid-email","username":"JohnSmith","password":"secret password"}'

Testing User Login (POST /api/session)

Postman Step-by-Step Procedure

  1. Create New Request
    • Name it "User Login"
    • Set method to POST
    • URL: {{baseUrl}}/api/session
  2. Configure Headers
    • Content-Type: application/json
    • XSRF-TOKEN: {{xsrfToken}}
  3. Configure Body
    {
        "credential": "john.smith@gmail.com",
        "password": "secret password"
    }
  4. Add Tests
    pm.test("Status code is 200", function () {
        pm.response.to.have.status(200);
    });
    
    pm.test("Login successful", function () {
        const responseJson = pm.response.json();
        pm.expect(responseJson.user).to.have.property('id');
        pm.expect(responseJson.user.email).to.eql('john.smith@gmail.com');
    });
    
    if (pm.response.code === 200) {
        pm.environment.set("authToken", pm.response.headers.get("Set-Cookie"));
    }

cURL Step-by-Step Procedure

  1. Prepare Login Data
    cat > login.json << EOF
    {
        "credential": "john.smith@gmail.com",
        "password": "secret password"
    }
    EOF
  2. Send Login Request
    curl -X POST http://localhost:8000/api/session \
      -H "Content-Type: application/json" \
      -H "XSRF-TOKEN: $TOKEN" \
      -b cookies.txt \
      -c cookies.txt \
      -d @login.json

Testing Session Management (GET /api/session)

Postman Step-by-Step Procedure

  1. Create New Request
    • Name it "Get Current Session"
    • Set method to GET
    • URL: {{baseUrl}}/api/session
  2. Configure Headers
    • Cookie: {{authToken}}
  3. Add Tests
    pm.test("Status code is 200", function () {
        pm.response.to.have.status(200);
    });
    
    pm.test("Session user data is correct", function () {
        const responseJson = pm.response.json();
        pm.expect(responseJson.user).to.not.be.null;
        pm.expect(responseJson.user).to.have.property('email');
    });

cURL Step-by-Step Procedure

curl http://localhost:8000/api/session \
  -b cookies.txt

Testing Logout (DELETE /api/session)

Postman Step-by-Step Procedure

  1. Create New Request
    • Name it "Logout"
    • Set method to DELETE
    • URL: {{baseUrl}}/api/session
  2. Configure Headers
    • XSRF-TOKEN: {{xsrfToken}}
    • Cookie: {{authToken}}
  3. Add Tests
    pm.test("Status code is 200", function () {
        pm.response.to.have.status(200);
    });
    
    pm.test("Logout successful", function () {
        const responseJson = pm.response.json();
        pm.expect(responseJson.message).to.eql('success');
    });
    
    pm.environment.set("authToken", null);

cURL Step-by-Step Procedure

curl -X DELETE http://localhost:8000/api/session \
  -H "XSRF-TOKEN: $TOKEN" \
  -b cookies.txt

Creating a Complete Test Flow

Now that we understand how to test each endpoint individually, let's create a complete test flow that simulates a user's journey through our application.

Postman Collection Runner Setup

  1. Organize Requests
    • Put requests in this order:
      1. User Registration
      2. User Login
      3. Get Current Session
      4. Logout
  2. Configure Runner
    • Click "Runner" in Postman
    • Select your collection
    • Set environment to "Local Development"
    • Enable "Keep variable values"

cURL Complete Flow Script

#!/bin/bash
# Save as test-flow.sh

echo "Starting API test flow..."

# Get CSRF token
./get-csrf.sh

# Register new user
echo "Testing registration..."
curl -X POST http://localhost:8000/api/users \
  -H "Content-Type: application/json" \
  -H "XSRF-TOKEN: $TOKEN" \
  -b cookies.txt \
  -c cookies.txt \
  -d @register.json

# Login
echo "Testing login..."
curl -X POST http://localhost:8000/api/session \
  -H "Content-Type: application/json" \
  -H "XSRF-TOKEN: $TOKEN" \
  -b cookies.