n8n Automation

n8n API Integration: REST, GraphQL & OAuth Flows

Petru Constantin
••14 min read
#n8n#API integration#REST#GraphQL#OAuth#automation

Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the n8n 2.47 (stable channel) documentation.

n8n API Integration Patterns: REST, GraphQL, and OAuth Workflows

API integrations are fundamental to workflow automation. This guide covers essential patterns for integrating REST APIs, GraphQL endpoints, and OAuth-protected services in n8n.

REST API Patterns

Basic HTTP Request Configuration

HTTP Request node
  Method: POST
  URL: https://api.example.com/v1/users
  Authentication: Predefined Credential Type when n8n has a credential for the service,
                  otherwise a generic credential such as Header Auth
  Send Headers: on
    X-Request-ID = {{ $execution.id }}
  Send Body: on (JSON)
    name  = {{ $json.name }}
    email = {{ $json.email }}
  Options
    Timeout: 30000
    Redirects: follow, Max Redirects: 5
Keep tokens in the credential, not in a header typed into the node.

Dynamic URL Building

// Code node "Build URL", mode: Run Once for Each Item
// n8n 2.x blocks $env in the Code node by default, so the base URL is a constant here.
const BASE_URL = 'https://api.example.com';
const VERSION = 'v2';
const { resourceType, resourceId, filters = {}, pagination, method = 'GET' } = $json;
 
const params = new URLSearchParams();
for (const [key, value] of Object.entries(filters)) {
  if (value !== null && value !== undefined) params.append(key, String(value));
}
if (pagination) {
  params.append('page', String(pagination.page ?? 1));
  params.append('limit', String(pagination.limit ?? 50));
}
 
// encodeURIComponent keeps "../" or "?" in an ID from changing the path
const path = [VERSION, encodeURIComponent(resourceType), resourceId ? encodeURIComponent(resourceId) : null]
  .filter(Boolean)
  .join('/');
const query = params.toString();
 
return { json: { url: `${BASE_URL}/${path}${query ? `?${query}` : ''}`, method } };

Response Handling and Error Management

// HTTP Request node before this one: Options > Response > Include Response Headers and Status,
// and Never Error, so 4xx/5xx responses reach this node instead of stopping the workflow.
// Code node "Handle Response", mode: Run Once for Each Item
const { statusCode, headers = {}, body } = $json;
const retryableCodes = [408, 429, 500, 502, 503, 504];
 
if (statusCode >= 200 && statusCode < 300) {
  const remaining = headers['x-ratelimit-remaining'];
  return {
    json: {
      success: true,
      statusCode,
      data: body,
      requestId: headers['x-request-id'] ?? null,
      rateLimitRemaining: remaining != null ? Number(remaining) : null,
    },
  };
}
 
if (retryableCodes.includes(statusCode)) {
  // Retry-After is either a number of seconds or an HTTP date
  const retryAfter = headers['retry-after'];
  let retryAfterSeconds = 60;
  if (retryAfter != null) {
    const seconds = Number(retryAfter);
    retryAfterSeconds = Number.isFinite(seconds)
      ? seconds
      : Math.max(0, Math.ceil((Date.parse(retryAfter) - Date.now()) / 1000)) || 60;
  }
  return {
    json: { success: false, retryable: true, statusCode, retryAfterSeconds, error: body?.message ?? 'Server error' },
  };
}
 
return {
  json: {
    success: false,
    retryable: false,
    statusCode,
    error: body?.message ?? body?.error ?? 'Request failed',
    details: body?.errors ?? body?.details ?? null,
  },
};

Pagination Handling

HTTP Request node > Add Option > Pagination
 
  Cursor returned in the response body:
    Pagination Mode: Update a Parameter in Each Request
    Type: Query    Name: cursor    Value: {{ $response.body.meta.endCursor }}
 
  Page numbers ($pageCount starts at 0):
    Pagination Mode: Update a Parameter in Each Request
    Type: Query    Name: page      Value: {{ $pageCount + 1 }}
 
  Next URL returned in the response:
    Pagination Mode: Response Contains Next URL
    Next URL: {{ $response.body.next }}
 
Page size goes in the main Send Query Parameters (for example limit = 100), not in Options.
Set the node's stop condition on the field your API uses to say there are no more pages
(for example an empty cursor or hasNextPage = false).

Batch API Requests

// Code node "Build Batches", mode: Run Once for All Items
// For APIs with a batch endpoint: groups input items into payloads of 50 requests.
// For APIs without one, use the HTTP Request option Batching instead.
const BATCH_SIZE = 50;
const records = $input.all().map(item => item.json);
 
const out = [];
for (let i = 0; i < records.length; i += BATCH_SIZE) {
  const batch = records.slice(i, i + BATCH_SIZE);
  out.push({
    json: {
      batchIndex: out.length,
      batch: {
        requests: batch.map((body, index) => ({
          id: String(index),
          method: 'POST',
          url: '/api/v1/resource',
          body,
        })),
      },
    },
  });
}
return out;

GraphQL Integration

Basic GraphQL Query

GraphQL node
  Authentication: Predefined Credential Type when n8n has one for the API,
                  otherwise a generic credential such as Header Auth
  HTTP Request Method: POST
  Endpoint: https://api.example.com/graphql
  Request Format: JSON
  Query:
    query GetUsers($first: Int!, $after: String) {
      users(first: $first, after: $after) {
        edges { node { id name email createdAt } cursor }
        pageInfo { hasNextPage endCursor }
      }
    }
  Variables: {"first": 50, "after": null}
             (on the next page, set after to the previous response's pageInfo.endCursor)
  Response Format: JSON
 
With an HTTP Request node instead: POST to the same endpoint with the JSON body
{ "query": "...", "variables": { "first": 50, "after": null } }, built by a Code node
like the one in the next section.

GraphQL Mutation with Variables

// Code node "Build Mutation", mode: Run Once for Each Item
// Output: { query, variables }, the JSON body for the GraphQL request.
const mutation = `
  mutation CreateOrder($input: CreateOrderInput!) {
    createOrder(input: $input) {
      order {
        id
        status
        total
        items { productId quantity price }
      }
      errors { field message }
    }
  }
`;
 
// Values travel in variables, never concatenated into the query string
const variables = {
  input: {
    customerId: $json.customerId,
    items: ($json.items ?? []).map(item => ({
      productId: item.productId,
      quantity: item.quantity,
    })),
    shippingAddress: {
      street: $json.address?.street,
      city: $json.address?.city,
      state: $json.address?.state,
      postalCode: $json.address?.postalCode,
      country: $json.address?.country,
    },
  },
};
 
return { json: { query: mutation, variables } };

GraphQL Error Handling

// Code node "Handle GraphQL Response", mode: Run Once for Each Item
// GraphQL APIs often return HTTP 200 with an errors array, so check the body.
const response = $json;
 
if (Array.isArray(response.errors) && response.errors.length > 0) {
  const errors = response.errors.map(err => ({
    message: err.message,
    path: err.path?.join('.') ?? null,
    code: err.extensions?.code ?? null,
  }));
 
  // Error codes are API-specific: take this list from your API's documentation
  const retryableCodes = ['INTERNAL_SERVER_ERROR', 'TIMEOUT', 'RATE_LIMITED'];
 
  return {
    json: {
      success: false,
      errors,
      retryable: errors.some(e => retryableCodes.includes(e.code)),
      partialData: response.data ?? null, // GraphQL can return partial data with errors
    },
  };
}
 
return { json: { success: true, data: response.data } };

GraphQL Subscriptions (via Webhook)

// Many GraphQL APIs run subscriptions over WebSockets, which a Webhook node can't hold open.
// When the service can instead POST events to a URL, point it at a Webhook node and
// process them here.
// Code node "Process Order Event", mode: Run Once for All Items
return $input.all()
  .map(item => item.json.body ?? {})
  .filter(event => event.type === 'orderUpdated' && event.data?.orderUpdated)
  .map(event => {
    const order = event.data.orderUpdated;
    return {
      json: {
        orderId: order.id,
        newStatus: order.status,
        updatedAt: order.updatedAt,
        requiresAction: ['PAYMENT_FAILED', 'CANCELLED'].includes(order.status),
      },
    };
  });

OAuth Authentication Flows

If n8n only has to call an API as one account, you don't need these nodes: pick the generic OAuth2 API credential in the HTTP Request node and n8n stores the tokens for you. The pattern below is for workflows that run the authorization code flow for their own end users. The client secret stays in an n8n credential (Basic Auth with the client ID and secret on the token request), never in a Code node.

OAuth 2.0 Authorization Code Flow

// Code node "Start Authorization", mode: Run Once for Each Item
// Self-hosted: allow the crypto module with NODE_FUNCTION_ALLOW_BUILTIN=crypto
// (n8n Cloud makes crypto available). Static data is saved only when a published
// workflow runs from its trigger, so test this flow through the production URL.
const crypto = require('crypto');
 
const AUTHORIZE_URL = 'https://auth.example.com/oauth/authorize'; // from the provider's docs
const CLIENT_ID = 'your-client-id';                                // public identifier, not a secret
const REDIRECT_URI = 'https://n8n.example.com/webhook/oauth/callback';
 
const state = crypto.randomBytes(32).toString('hex');
 
const staticData = $getWorkflowStaticData('global');
staticData.oauthStates = staticData.oauthStates ?? {};
 
// Drop states older than 10 minutes
const tenMinutesAgo = Date.now() - 10 * 60 * 1000;
for (const [key, value] of Object.entries(staticData.oauthStates)) {
  if (value.created < tenMinutesAgo) delete staticData.oauthStates[key];
}
staticData.oauthStates[state] = { created: Date.now(), userId: $json.userId };
 
const params = new URLSearchParams({
  client_id: CLIENT_ID,
  redirect_uri: REDIRECT_URI,
  response_type: 'code',
  scope: 'read write',
  state,
});
 
return { json: { authorizationUrl: `${AUTHORIZE_URL}?${params}`, state } };

OAuth Token Exchange

// Code node "Verify State", mode: Run Once for Each Item, after the callback Webhook (GET).
// The next HTTP Request node POSTs this body form-urlencoded to the token endpoint and
// authenticates the client with a Basic Auth credential holding the client ID and secret.
const { code, state, error } = $json.query ?? {};
if (error) throw new Error(`Authorization failed: ${error}`);
 
const staticData = $getWorkflowStaticData('global');
const saved = state ? staticData.oauthStates?.[state] : undefined;
if (!saved || Date.now() - saved.created > 10 * 60 * 1000) {
  throw new Error('Invalid or expired state parameter');
}
delete staticData.oauthStates[state]; // a state value works once
 
return {
  json: {
    userId: saved.userId,
    body: {
      grant_type: 'authorization_code',
      code,
      redirect_uri: 'https://n8n.example.com/webhook/oauth/callback',
    },
  },
};

Token Refresh Handler

// Code node "Check Token Expiry", mode: Run Once for Each Item
// Input: a stored token record. Output: whether to refresh, and the body for an
// HTTP Request node that uses the same Basic Auth client credential.
// The access token itself is not copied into the output, to keep it out of execution data.
const t = $json;
const expiresAt = t.expiresAt ?? (t.issuedAt + t.expiresIn * 1000);
const needsRefresh = expiresAt - Date.now() < 5 * 60 * 1000; // within 5 minutes of expiry
 
if (!needsRefresh) {
  return { json: { userId: t.userId, needsRefresh: false } };
}
if (!t.refreshToken) {
  throw new Error('Token expired and no refresh token is available');
}
 
return {
  json: {
    userId: t.userId,
    needsRefresh: true,
    body: { grant_type: 'refresh_token', refresh_token: t.refreshToken },
  },
};

OAuth Token Storage

// Code node "Prepare Token Record", mode: Run Once for Each Item (crypto, see above)
// Input: the token endpoint's JSON response (access_token, token_type, expires_in,
// refresh_token, scope). Tokens are secrets: store them where they are encrypted
// (a secrets manager or an encrypted column) and log only the short hash.
const crypto = require('crypto');
const tokens = $json;
const now = Date.now();
 
const tokenHash = crypto
  .createHash('sha256')
  .update(String(tokens.access_token))
  .digest('hex')
  .slice(0, 8);
 
return {
  json: {
    userId: $('Verify State').item.json.userId,
    provider: 'example_provider',
    accessToken: tokens.access_token,
    refreshToken: tokens.refresh_token ?? null,
    tokenType: tokens.token_type ?? 'Bearer',
    scope: tokens.scope ?? null,
    issuedAt: now,
    expiresAt: tokens.expires_in ? now + tokens.expires_in * 1000 : null,
    metadata: { tokenHash, createdAt: new Date(now).toISOString() },
  },
};

Rate Limiting and Throttling

Request Throttling

Built-in ways to stay under a provider's rate limit
 
  HTTP Request node > Options > Batching
    Items per Batch: 10
    Batch Interval (ms): 1000
 
  Node Settings > Retry On Fail (for 429 and 5xx responses)
    Max Tries: 3
    Wait Between Tries (ms): 1000
 
  Loop Over Items (batch size), then a Wait node
    Resume: After Time Interval    Wait Amount: 1    Wait Unit: Seconds
 
Take the numbers from the provider's current rate-limit documentation:
limits differ per plan and per endpoint, and they change.

Adaptive Rate Limiting

// Code node "Read Rate Limit", mode: Run Once for Each Item
// Input: HTTP Request output with Include Response Headers and Status turned on.
// Output: rateLimit.waitSeconds for a following Wait node
// (Resume: After Time Interval, Wait Amount: {{ $json.rateLimit.waitSeconds }}, Wait Unit: Seconds).
// Header names, and whether "reset" is a Unix timestamp or seconds left, differ per API.
const headers = $json.headers ?? {};
const num = v => (v == null || v === '' ? null : Number(v));
 
const info = {
  limit: num(headers['x-ratelimit-limit'] ?? headers['x-rate-limit-limit']),
  remaining: num(headers['x-ratelimit-remaining'] ?? headers['x-rate-limit-remaining']),
  reset: num(headers['x-ratelimit-reset'] ?? headers['x-rate-limit-reset']),
  retryAfter: num(headers['retry-after']),
};
 
let waitSeconds = 0;
if (info.retryAfter) {
  waitSeconds = info.retryAfter;
} else if (info.remaining === 0 && info.reset) {
  // large values are treated as a Unix timestamp, small ones as seconds left
  waitSeconds = info.reset > 1e9 ? info.reset - Math.floor(Date.now() / 1000) : info.reset;
} else if (info.limit && info.remaining !== null && info.remaining < info.limit * 0.1) {
  waitSeconds = 1; // less than 10% left: slow down
}
 
return { json: { ...$json, rateLimit: { ...info, waitSeconds: Math.max(0, waitSeconds) } } };

Webhook Integration

Webhook Payload Processing

// Code node "Normalize Webhook", mode: Run Once for Each Item, after a Webhook node.
// The Webhook node outputs { headers, params, query, body }; header names are lowercase.
// Verify the provider's signature before trusting the payload: Stripe-Signature,
// X-Hub-Signature-256 (GitHub) and X-Shopify-Hmac-Sha256 are all computed over the raw
// request body, so that check needs the Webhook node's Raw Body option.
// Deduplicate on the event or delivery ID: providers can deliver the same event twice.
const { headers = {}, body = {} } = $json;
 
let source = 'unknown';
if (headers['x-github-event']) source = 'github';
else if (headers['x-shopify-hmac-sha256']) source = 'shopify';
else if (headers['stripe-signature']) source = 'stripe';
 
let event;
switch (source) {
  case 'github':
    event = {
      type: headers['x-github-event'],
      deliveryId: headers['x-github-delivery'] ?? null,
      action: body.action ?? null,
      repository: body.repository?.full_name ?? null,
      sender: body.sender?.login ?? null,
      data: body,
    };
    break;
  case 'stripe':
    // snapshot events carry the object in data.object
    event = {
      type: body.type,
      eventId: body.id ?? null,
      livemode: body.livemode ?? null,
      resourceId: body.data?.object?.id ?? null,
      data: body.data?.object ?? body,
    };
    break;
  case 'shopify':
    event = {
      type: headers['x-shopify-topic'] ?? null,
      webhookId: headers['x-shopify-webhook-id'] ?? null,
      data: body,
    };
    break;
  default:
    event = { type: 'unknown', data: body };
}
 
return { json: { source, receivedAt: new Date().toISOString(), event } };

Best Practices Summary

  1. Handle errors in node settings: Retry On Fail for transient failures, On Error: Continue (using error output) for a fallback branch, and an error workflow that starts with the Error Trigger.
  2. Respect rate limits: the HTTP Request Batching option, Loop Over Items with a Wait node, and the provider's Retry-After header.
  3. Use the HTTP Request node's built-in pagination before writing a loop by hand.
  4. Keep secrets in credentials: n8n 2.x blocks $env in the Code node by default, and a token typed into a node ends up in the workflow JSON.
  5. Verify webhook signatures on the raw body and deduplicate on the event or delivery ID.
  6. Validate response structure before processing, including the errors array in GraphQL responses that return HTTP 200.
  7. Set a Timeout on every HTTP Request node.

With these patterns, the HTTP Request, GraphQL, Webhook and Code nodes cover the REST, GraphQL and OAuth integrations described in this guide on current n8n 2.x.


From production

DeviDevs' own e-Factura integration with the Romanian tax authority's API (ANAF) authenticates with OAuth2 and refreshes the token automatically when a call comes back with 401; after 3 failures, a circuit breaker pauses uploads for 30 minutes and queues the invoices instead. The code behind the email-events webhook on devidevs.com verifies the provider's HMAC-SHA256 signature over the message ID, the timestamp and the raw body, rejects anything older than 5 minutes (protection against replayed requests), compares signatures in constant time and rejects every request when no secret is configured. Those four signature checks are the ones worth reproducing on any webhook you expose from n8n.

Official references

Related on this site: AI-Powered n8n Workflows: Integration Patterns, n8n Database Integration: PostgreSQL, MongoDB & More, n8n Slack Integration: Workflow Automations. More articles in the n8n Automation category.

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.