如何为 n8n 创建 FastAPI 自定义节点?

解读

面试官抛出这道题,并不是想听你“把 FastAPI 跑起来”就算完,而是考察三件事:

  1. 你是否真正理解 n8n 的节点生态(Node Type、Credentials、Routing、UI 描述文件、社区打包规范);
  2. 能否把 FastAPI 的高性能异步能力封装成“可被 n8n 低代码流程引擎直接调用”的可复用节点,而不是简单暴露一个 HTTP 接口;
  3. 在国内企业落地时,如何兼顾私有部署、国产操作系统、信创中间件、内网证书、代理穿透、合规审计等现实约束。

一句话:让你用 FastAPI 做“发动机”,但成品必须像原厂节点一样能拖、能配、能跑、能打包、能上架。

知识点

  1. n8n 节点规范
    • 节点目录结构:nodes/NodeName/NodeName.node.ts、credentials/NodeNameApi.credentials.ts、svg 图标、package.json 必须带 n8n-nodes- 前缀。
    • 节点类需继承 INodeType,实现 description、execute、hook 方法;description 里定义 displayName、properties、defaults、inputs/outputs。
    • 凭证(Credentials)与节点解耦,支持 OAuth2、JWT、Basic、Query Auth 等;FastAPI 端需给出 /token 交换接口与 /docs 里可见的授权范围。
  2. FastAPI 侧技术点
    • 用 async def 编写端点,返回模型全部继承 pydantic.BaseModel,字段与 n8n 的“选项参数”一一对应,避免二次映射。
    • 为 n8n 提供“批量操作”接口:/batch,支持一次性传入 items[],减少往返;内部用 asyncio.gather 并发,限流用 aiometer 或 semaphore。
    • 统一错误模型:{“error”: true, “message”: “”, “code”: “”},方便 n8n 节点在 execute() 里直接抛出 NodeApiError,前端可识别。
    • 开放 /openapi.json 并自定义 x-n8n-icon、x-n8n-category 扩展字段,后续可用脚本自动生成 description 的 json 片段,降低手写成本。
  3. 国产环境适配
    • 内网无法拉取 GitHub,需要把 n8n 社区 CLI(npm install -g n8n-nodes-dev)提前做成离线包,放在私有 Nexus;
    • 若走信创 OS(麒麟、统信),FastAPI 需使用 Python3.9+ 的 RPM 自编译包,禁用 uvloop(有内核适配问题),gunicorn worker 类改用 uvicorn.workers.UvicornWorker;
    • 证书双向校验:FastAPI 启动参数 --ssl-keyfile --ssl-certfile,n8n 凭证里把 CA 证书粘到 credentials 的 “CA Cert” 字段,节点里读取后塞进 aiohttp.TCPConnector(ssl=ssl_context)。

答案

下面给出一个可直接落地、通过社区打包校验的“最小可用范例”,分三步:FastAPI 服务 → n8n 凭证 → n8n 节点。

步骤 1:FastAPI 微服务(内网地址 https://fastapi-inner.local)

# main.py
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
from typing import List
import asyncio, aiometer, jwt, time

app = FastAPI(title="n8nCustomNode", version="1.0.0")

# 统一返回模型
class Resp(BaseModel):
    success: bool
    data: dict = None
    error: str = None

# 请求模型
class Item(BaseModel):
    id: int
    msg: str = Field(..., max_length=20)

# 简单 JWT 校验
def verify_token(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, "super-secret", algorithms=["HS256"])
        return payload
    except Exception:
        raise HTTPException(401, "Invalid token")

# 单条处理
async def _process_one(item: Item) -> dict:
    await asyncio.sleep(0.1)  # 模拟 IO
    if "失败" in item.msg:
        raise ValueError("敏感词触发")
    return {"id": item.id, "answer": f"FastAPI 收到:{item.msg}"}

# 批量接口
@app.post("/batch", response_model=Resp)
async def batch(items: List[Item], _=Depends(verify_token)):
    semaphore = asyncio.Semaphore(10)  # 并发上限
    async def run(item):
        async with semaphore:
            return await _process_one(item)
    try:
        results = await aiometer.run_all([lambda i=x: run(i) for x in items], max_at_once=10)
        return Resp(success=True, data={"results": results})
    except ValueError as e:
        return Resp(success=False, error=str(e))

步骤 2:凭证文件(credentials/FastApiInnerApi.credentials.ts)

import { IAuthenticateGeneric, ICredentialType, INodeProperties } from 'n8n-workflow';

export class FastApiInnerApi implements ICredentialType {
    name = 'fastApiInnerApi';
    displayName = 'FastAPI 内网服务';
    properties: INodeProperties[] = [
        {
            displayName: 'Token',
            name: 'token',
            type: 'string',
            default: '',
            typeOptions: { password: true },
        },
        {
            displayName: 'CA 证书',
            name: 'caCert',
            type: 'string',
            default: '',
            typeOptions: { rows: 4 },
            description: '若走双向 TLS,请粘贴根证书',
        },
    ];
    authenticate: IAuthenticateGeneric = {
        type: 'generic',
        properties: {
            headers: {
                Authorization: '={{"Bearer " + $credentials.token}}',
            },
        },
    };
}

步骤 3:节点文件(nodes/FastApiBatch/FastApiBatch.node.ts)

import { IExecuteFunctions } from 'n8n-core';
import {
    INodeExecutionData,
    INodeType,
    INodeTypeDescription,
    NodeApiError,
} from 'n8n-workflow';
import { OptionsWithUri } from 'request';

export class FastApiBatch implements INodeType {
    description: INodeTypeDescription = {
        displayName: 'FastAPI 批处理',
        name: 'fastApiBatch',
        group: ['transform'],
        version: 1,
        description: '调用内网 FastAPI 批量服务',
        defaults: { name: 'FastAPI批处理' },
        inputs: ['main'],
        outputs: ['main'],
        credentials: [{ name: 'fastApiInnerApi', required: true }],
        properties: [
            {
                displayName: '输入字段名',
                name: 'inputField',
                type: 'string',
                default: 'msg',
                description: '要发送的字段',
            },
        ],
    };

    async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
        const items = this.getInputData();
        const inputField = this.getNodeParameter('inputField', 0) as string;
        const credentials = await this.getCredentials('fastApiInnerApi');

        const body = {
            items: items.map((item, i) => ({
                id: i,
                msg: item.json[inputField] || '',
            })),
        };

        const options: OptionsWithUri = {
            method: 'POST',
            uri: 'https://fastapi-inner.local/batch',
            json: true,
            body,
            headers: { Authorization: `Bearer ${credentials.token}` },
            // 若需 CA
            // ca: credentials.caCert as string,
        };

        const response = await this.helpers.request(options);
        if (!response.success) {
            throw new NodeApiError(this.getNode(), response);
        }

        // 把返回结果映射回 n8n item
        return [items.map((item, i) => ({
            json: { ...item.json, answer: response.data.results[i].answer },
        }))];
    }
}

打包验证

  1. 项目根目录 npm install n8n-nodes-dev -g(离线环境提前缓存 tgz)。
  2. n8n-nodes-dev build,生成 *.tar.gz。
  3. 在私有 n8n 实例“社区节点”页面上传,或直接把 dist 目录挂到 N8N_CUSTOM_EXTENSIONS 环境变量。
  4. 新建工作流,拖入“FastAPI批处理”节点,配置凭证、输入字段,运行后可在 UI 看到返回的 answer 字段,即完成闭环。

拓展思考

  1. 动态 schema:FastAPI 的 /openapi.json 可在启动时注入 x-n8n-properties 扩展,n8n 节点里写一段 codegen 脚本,把 OpenAPI 直接转成 description,实现“零手写”节点;这在需要频繁变更字段的业务系统(如国产 ERP 接口)里能节省 70% 维护量。
  2. 流式返回:若 FastAPI 端点用 StreamingResponse 逐条吐数据,n8n 节点需把 execute 改成 async *execute() 生成器,配合 this.getInputData() 的长度预估,边接收边向下游节点推送,内存占用从 O(n) 降到 O(1)。
  3. 国产加密:国密 SM2/SM3 场景,FastAPI 侧可用 gmssl 库,把签名放在响应头 X-SM3-Digest;n8n 节点在 execute() 里用 node-forge 的 sm3 实现验签,满足金融、政务内网合规。
  4. 高可用:n8n 本身无状态,FastAPI 用 gunicorn+uvicorn 多 worker,前面挂国产负载(如 TongHttp),再注册到 Consul,n8n 凭证里支持 Consul-Template 动态拉取上游地址,实现节点级服务发现。
  5. 开源合规:若计划把节点贡献到 n8n 社区,需注意 GPL-3.0 传染性;企业可单独维护闭源 FastAPI 服务,只开源节点壳,保持许可证隔离。

掌握以上思路,面试时你不仅能给出“能跑”的 Demo,更能把国内私有部署、信创、合规、性能、可维护性全部讲到,面试官基本会给出“可独立负责一条产品线”的评价。