Intermediate N8n Tutorial 4 min read

n8n Webhook and API Automation: Connect AI to Any Service

#n8n #webhook #api #automation #http-request #integration

Why Webhooks + APIs Matter for AI Workflows

An AI agent that can only respond to prompts is limited. The real power comes from connecting AI to your actual tools: summarize a GitHub issue, post findings to Slack, update a Notion database, or trigger actions based on external events.

n8n makes this straightforward — every external service is a node, and your AI Agent node can call HTTP Request nodes as tools.

Pattern 1: Webhook → AI → Notify

The most common pattern: receive a webhook from an external service, process it with AI, and send the result somewhere.

Receive a GitHub Issue → AI Summary → Slack

GitHub Webhook (issue opened)

AI Agent (summarize + classify)

Slack (post to #triage channel)

Step 1: GitHub Webhook

  1. Add a Webhook node:
    • HTTP Method: POST
    • Path: github-issues
  2. In GitHub repo settings → Webhooks → add your URL
  3. Events: Issues

Step 2: AI Agent

Add an AI Agent node:

  • Chat Model: OpenAI gpt-4o-mini
  • System prompt:
    You are a triage assistant. Analyze GitHub issues and return a JSON object with:
    - "summary": one sentence describing the issue
    - "priority": "high" | "medium" | "low"
    - "type": "bug" | "feature" | "question" | "other"
  • User message:
    Issue title: {{ $json.body.issue.title }}
    Issue body: {{ $json.body.issue.body }}
    Author: {{ $json.body.issue.user.login }}

Step 3: Parse AI Output

Add a Code node to parse the JSON response:

const raw = $input.item.json.output;
// Extract JSON from the response
const match = raw.match(/\{[\s\S]*\}/);
const parsed = JSON.parse(match[0]);
return { json: parsed };

Step 4: Slack Notification

Add a Slack node:

  • Operation: Send a message
  • Channel: #triage
  • Message:
    *New Issue:* {{ $('Webhook').item.json.body.issue.title }}
    *Priority:* {{ $json.priority }} | *Type:* {{ $json.type }}
    *Summary:* {{ $json.summary }}
    *Link:* {{ $('Webhook').item.json.body.issue.html_url }}

Pattern 2: AI Agent with HTTP Request Tools

Give your AI Agent the ability to call external APIs autonomously:

Setup: AI Agent with Custom Tools

  1. Add an AI Agent node
  2. Inside the agent, add HTTP Request Tool nodes:

Tool: Search Products

Name: search_products
Description: Search the product catalog by keyword. Returns matching products with prices.
Method: GET
URL: https://api.mystore.com/products?search={{ $fromAI('query') }}
Headers: Authorization: Bearer {{ $credentials.apiKey }}

Tool: Get Order Status

Name: get_order_status
Description: Look up order status by order ID.
Method: GET
URL: https://api.mystore.com/orders/{{ $fromAI('order_id') }}

System Prompt:

You are a customer support agent for MyStore. You have access to:
- search_products: search product catalog
- get_order_status: check order status

Always use tools to get current information before answering.

The agent will autonomously call these tools when needed.


Pattern 3: Scheduled AI Report

Run an AI workflow on a schedule to generate and deliver reports.

Schedule Trigger (every Monday 9am)

HTTP Request (fetch data from API)

AI Agent (analyze and write report)

Gmail / Slack (deliver report)

Step 1: Schedule Trigger

  • Set to Every Week on Monday at 9:00 AM

Step 2: Fetch Data

Add an HTTP Request node:

  • Method: GET
  • URL: https://api.analytics.com/reports/weekly
  • Authentication: Header Auth with your API key
  • Response: JSON

Step 3: AI Analysis

Add an AI Agent node:

  • System prompt:
    You are a business analyst. Write a concise weekly performance summary.
    Structure:
    1. Key Metrics (bullet points)
    2. Notable Changes (what increased/decreased significantly)
    3. Action Items (3 recommendations)
    Keep it under 300 words, formatted for email.
  • User message:
    Here is this week's data:
    {{ JSON.stringify($json) }}

Step 4: Send Email

Add a Gmail (or SendGrid) node:

  • To: [email protected]
  • Subject: Weekly AI Report — {{ $now.toFormat('yyyy-MM-dd') }}
  • Body: {{ $('AI Agent').item.json.output }}

Handling API Authentication

n8n supports all common auth patterns:

API Key (Header):

  1. Go to Credentials → New → HTTP Request API
  2. Add header: Authorization: Bearer YOUR_KEY
  3. Reference in HTTP Request node: select your credential

OAuth2: n8n has built-in OAuth2 support for Google, GitHub, Slack, Notion, and 100+ services. No manual token handling needed — just connect once via the UI.

Basic Auth:

Username: {{ $env.API_USERNAME }}
Password: {{ $env.API_PASSWORD }}

Use n8n’s Environment Variables (Settings → Variables) to store secrets — never hardcode them in node configurations.


Error Handling in API Workflows

Robust API integrations need error handling:

Add Error Routing:

  1. On any node, click the node settings gear
  2. Enable Continue on Fail
  3. Add an If node after it to check for errors:
    Condition: {{ $json.error }} exists
  4. Route errors to a Slack notification or log file

Retry Logic: For transient API failures, use the Wait node + Loop pattern:

// Code node: check if retry is needed
const statusCode = $input.item.json.statusCode;
if (statusCode === 429 || statusCode >= 500) {
  return { json: { retry: true, waitSeconds: 30 } };
}
return { json: { retry: false } };

Global Error Trigger: Create a separate workflow with an Error Trigger node to catch all failures across your n8n instance and send alerts.


Real-World Example: AI-Powered Content Pipeline

RSS Trigger (new blog posts every hour)

HTTP Request (fetch full article content)

AI Agent (summarize + extract keywords)

HTTP Request (POST to Notion database)

Slack (notify team)

RSS → AI Summary → Notion:

// AI Agent System Prompt
You are a content curator. For each article:
1. Write a 2-sentence summary
2. Extract 5 keywords
3. Rate relevance to "AI agents" from 1-10
Return JSON: { "summary": "...", "keywords": [...], "relevance": N }

Notion HTTP Request:

Method: POST
URL: https://api.notion.com/v1/pages
Headers:
  Authorization: Bearer {{ $credentials.notionToken }}
  Notion-Version: 2022-06-28
Body:
{
  "parent": { "database_id": "YOUR_DB_ID" },
  "properties": {
    "Title": { "title": [{ "text": { "content": "{{ $json.title }}" } }] },
    "Summary": { "rich_text": [{ "text": { "content": "{{ $json.summary }}" } }] },
    "Relevance": { "number": {{ $json.relevance }} }
  }
}

Frequently Asked Questions

How do I test webhooks locally?

Use ngrok to expose your local n8n instance:

ngrok http 5678

Use the ngrok URL as your webhook endpoint. Or use n8n’s built-in test webhook mode (the “Test” button activates a temporary URL).

Can I process multiple items in one workflow run?

Yes. Use Loop Over Items or enable Split In Batches on nodes that should process each item individually. The Merge node combines results from parallel branches.

How do I pass data between HTTP Request and AI Agent?

Data flows automatically through n8n’s item system. Reference previous node data with {{ $('NodeName').item.json.fieldName }}. For complex transformations, use a Code node in between.

What rate limits should I watch for?

Most APIs have rate limits. Add a Wait node (1–2 seconds) between iterations when looping over API calls. For Slack, the limit is 1 message/second. For OpenAI, monitor your TPM (tokens per minute) usage.

Can I call n8n webhooks from other n8n workflows?

Yes. Use an HTTP Request node in one workflow to call the webhook URL of another. This enables workflow composition — breaking complex pipelines into smaller, reusable sub-workflows.

Next Steps

Related Articles