n8n Masterclass IModule 6

6.1REST API Fundamentals for n8n Power Users

30 min 12 code blocks Practice Lab Quiz (4Q)

Lesson 6.1 — REST API Fundamentals for n8n Power Users

Every meaningful automation you'll ever build touches an API. When a Karachi e-commerce store pings your system after a Daraz order ships, that's an API call. When your n8n workflow grabs today's USD/PKR rate from a currency service and drops it into a WhatsApp message for your client, that's an API call. REST APIs are the universal language of the internet — and n8n is your universal translator. In this lesson you'll go from understanding what REST actually means to confidently hammering any API endpoint, handling auth headers, parsing JSON responses, and looping over paginated data — all without writing more than a handful of lines of JavaScript.

What You'll Learn

  • What REST means and why it matters for automation (GET, POST, PUT, DELETE)
  • How to configure n8n's HTTP Request node for any API
  • Authentication patterns: API keys, Bearer tokens, OAuth2, and Basic auth
  • Reading and mapping JSON responses with n8n expressions
  • Handling paginated APIs (cursor-based and page-number-based)
  • Rate limiting: how to not get your IP banned
  • Real-world API workflow: fetching open exchange rates and writing to Google Sheets

Core Concepts

REST in Plain English

REST (Representational State Transfer) is a convention — a way that web services agree to communicate. Every REST API has:

  • Base URL — the server address, e.g., https://api.openexchangerates.org/api
  • Endpoint — the specific resource, e.g., /latest.json
  • Method — what you want to do:
    • GET — fetch data (read-only)
    • POST — create something new (send a body)
    • PUT / PATCH — update existing data
    • DELETE — remove something
  • Headers — metadata about the request (auth tokens, content type)
  • Body — the payload you send with POST/PUT requests (usually JSON)
  • Response — what the server sends back (JSON, XML, plain text)

HTTP Status Codes You Must Know

CodeMeaningAction in n8n
200OK — successContinue workflow
201CreatedParse the new resource ID
400Bad Request — your payload is wrongCheck the request body
401Unauthorized — bad credentialsRotate your API key
403Forbidden — no permissionCheck account plan/scope
404Not Found — wrong endpointVerify URL
429Too Many RequestsAdd a Wait node
500Server ErrorRetry with exponential backoff

Step-by-Step: Configuring the HTTP Request Node

Step 1 — Add an HTTP Request Node

In your n8n canvas, click + and search for HTTP Request. Drop it into your workflow after your trigger.

Step 2 — Set the Method and URL

code
Method: GET
URL: https://api.exchangerate-api.com/v4/latest/USD

This free endpoint returns all exchange rates relative to USD — including PKR.

Step 3 — Authentication

Click the Authentication dropdown. Choose the right type:

Option A — API Key in Header (most common)

code
Authentication: Header Auth
Name: Authorization
Value: Bearer YOUR_API_KEY_HERE

Option B — API Key as Query Parameter

code
Authentication: Query Parameters
Name: app_id
Value: {{ $env.OPEN_EXCHANGE_APP_ID }}

Always store secrets in n8n Environment Variables (Settings > Variables), never hardcoded in the node. Use {{ $env.MY_SECRET }} to reference them.

Option C — Basic Auth

code
Authentication: Basic Auth
Username: your_username
Password: {{ $env.API_PASSWORD }}

Step 4 — Parse the Response

After execution, click on the HTTP Request node's output to inspect the JSON. Suppose the response looks like:

json
{
  "base": "USD",
  "rates": {
    "PKR": 278.45,
    "EUR": 0.92,
    "GBP": 0.79
  },
  "time_last_updated": 1711670400
}

In the next node (e.g., Set node), you reference fields like:

code
{{ $json.rates.PKR }}
{{ $json.base }}
{{ new Date($json.time_last_updated * 1000).toISOString() }}

Step 5 — Send a POST Request with a Body

code
Method: POST
URL: https://api.example.com/leads
Headers:
  Content-Type: application/json
  Authorization: Bearer {{ $env.CRM_API_KEY }}

Body (JSON):
{
  "name": "{{ $json.name }}",
  "email": "{{ $json.email }}",
  "source": "n8n-automation",
  "city": "Karachi"
}

In n8n, set Body Content Type to JSON and paste the above into the Body field with expression mode enabled.

Handling Pagination

Many APIs don't return all data in one request — they paginate. n8n handles this with a loop pattern.

Page-Number Pagination

code
URL: https://api.example.com/contacts?page={{ $node["Set"].json.currentPage }}&per_page=100

Build a workflow:

  1. Set node — initialize currentPage = 1, hasMore = true
  2. HTTP Request — fetch page
  3. IF node — check {{ $json.data.length > 0 }}
  4. If true: Set node — increment currentPage = {{ $node["Set"].json.currentPage + 1 }}
  5. Loop back to HTTP Request
  6. If false: Merge all collected data

Cursor-Based Pagination (e.g., HubSpot, Airtable)

javascript
// In a Code node after HTTP Request:
const nextCursor = $json.paging?.next?.after || null;
return [{ json: { cursor: nextCursor, hasMore: !!nextCursor } }];

Then pass cursor as a query parameter in the next request.

Rate Limiting — Don't Get Banned

Pakistan-based servers often have slower network conditions, making it tempting to fire requests in rapid bursts. Don't.

Add a Wait node between batches:

code
Wait: 1 second (fixed)

Or use n8n's Split In Batches node to process 10 records at a time with a 500ms wait between batches.

For APIs with strict limits (e.g., 60 req/min), use this expression in a Wait node:

code
{{ Math.ceil(($itemIndex + 1) / 60) * 1000 }}

This dynamically adds 1 second of delay every 60 items.

Full Workflow Example: Daily PKR Rate to Google Sheets

Here is a complete n8n workflow JSON you can import directly:

json
{
  "nodes": [
    {
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "parameters": {
        "rule": { "interval": [{ "field": "hours", "hoursInterval": 24 }] }
      },
      "position": [100, 300]
    },
    {
      "name": "Fetch PKR Rate",
      "type": "n8n-nodes-base.httpRequest",
      "parameters": {
        "method": "GET",
        "url": "https://api.exchangerate-api.com/v4/latest/USD",
        "responseFormat": "json"
      },
      "position": [300, 300]
    },
    {
      "name": "Extract Rate",
      "type": "n8n-nodes-base.set",
      "parameters": {
        "values": {
          "string": [
            { "name": "pkr_rate", "value": "={{ $json.rates.PKR }}" },
            { "name": "date", "value": "={{ new Date().toLocaleDateString('en-PK') }}" },
            { "name": "source", "value": "exchangerate-api.com" }
          ]
        }
      },
      "position": [500, 300]
    },
    {
      "name": "Append to Sheet",
      "type": "n8n-nodes-base.googleSheets",
      "parameters": {
        "operation": "append",
        "sheetId": "YOUR_SHEET_ID",
        "range": "Sheet1!A:C",
        "valueInputMode": "USER_ENTERED"
      },
      "position": [700, 300]
    }
  ]
}

Import this via the n8n canvas menu: Import from clipboard > paste JSON.

Practice Lab

Practice Lab

Task 1 — Weather API Integration Use the free Open-Meteo API (no API key required) to fetch today's weather for Karachi (latitude=24.8607&longitude=67.0011). Extract temperature, wind speed, and weather code. Log the output in a Set node and print it to the console with a Code node using console.log().

Task 2 — POST to a Mock CRM Use https://reqres.in/api/users as a test endpoint. Build a workflow that reads 3 rows from a Google Sheet (name, email, phone), then POSTs each row as a new user. Log the id returned in the response back to the sheet in a new column.

Task 3 — Paginated API Consumer Use the free JSONPlaceholder API: https://jsonplaceholder.typicode.com/posts — it returns 100 posts. Build a workflow that paginates through them in batches of 10, filters only posts where userId equals 3, and writes the filtered titles to a new Google Sheet tab. Hint: use Split In Batches + IF filter + Google Sheets Append.

Pakistan Case Study

Character: Farrukh Baig, 26-year-old freelancer from DHA Karachi. He manages social media accounts for 8 SME clients and needs to post daily USD/PKR rates as Instagram Story content for a currency exchange client.

The Problem: Farrukh was manually checking rates on Google Finance every morning at 9am, copying them into Canva, and posting — a 25-minute daily ritual worth zero intellectual value.

The n8n Solution:

  • Schedule Trigger at 08:30 AM PKT (UTC+5 = 03:30 UTC)
  • HTTP Request to Open Exchange Rates (free tier, 1,000 req/month)
  • Set node extracts PKR, EUR, GBP, AED rates
  • Code node formats a caption: "Today's rates (${date}): USD = PKR ${pkr}, EUR = PKR ${eur}, AED = PKR ${aed}"
  • HTTP Request to Canva API (or make.com Canva connector) to populate a template
  • Another HTTP Request to Facebook Graph API to schedule the post

Result: 25 minutes/day saved = 12.5 hours/month. At PKR 1,500/hour freelance rate = PKR 18,750/month recovered from one workflow. Farrukh now has this running for 4 currency clients, recovering PKR 75,000/month in productive time.

He charges each client PKR 5,000/month for "automated daily rate posts." Revenue: PKR 20,000/month from a 2-hour setup.

Key Takeaways

  • REST APIs use HTTP methods (GET/POST/PUT/DELETE) and return JSON — n8n's HTTP Request node handles all of them with zero code
  • Always store API keys in n8n Environment Variables — never hardcode secrets in nodes
  • Pagination requires a loop pattern: initialize a counter, fetch, check for more, increment, repeat
  • Rate limiting is a real constraint — use Wait nodes and Split In Batches to avoid 429 errors
  • Even a simple daily API fetch workflow can generate PKR 5,000–20,000/month in recurring client revenue

Next Lesson

In Lesson 6.2 — Webhook Workflows: Real-Time Triggers & Responses, you'll flip the model: instead of n8n calling external services, external services will call n8n. You'll build a live order notification system where a Daraz webhook fires your n8n workflow the moment a customer places an order — and you'll learn how to respond to the webhook synchronously with a custom payload.

Lesson Summary

Includes hands-on practice lab12 runnable code examples4-question knowledge check below

Quiz: REST API Fundamentals for n8n Power Users

4 questions to test your understanding. Score 60% or higher to pass.