当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

openapi-backend

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 夏高朗
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

CIStake to support us

Build, Validate, Route, Authenticate, and Mock using OpenAPI definitions.

OpenAPI Backend is a Framework-agnostic middleware tool for building beautiful APIs with OpenAPI Specification.

Features

Documentation

See DOCS.md

Quick Start

Full example projects included in the repo

npm install --save openapi-backend
import OpenAPIBackend from 'openapi-backend';

// create api with your definition file or object
const api = new OpenAPIBackend({ definition: './petstore.yml' });

// register your framework specific request handlers here
api.register({
  getPets: (c, req, res) => res.status(200).json({ result: 'ok' }),
  getPetById: (c, req, res) => res.status(200).json({ result: 'ok' }),
  validationFail: (c, req, res) => res.status(400).json({ err: c.validation.errors }),
  notFound: (c, req, res) => res.status(404).json({ err: 'not found' }),
});

// initalize the backend
api.init();

Express

import express from 'express';

const app = express();
app.use(express.json());
app.use((req, res) => api.handleRequest(req, req, res));
app.listen(9000);

See full Express example

See full Express TypeScript example

AWS Serverless (Lambda)

// API Gateway Proxy handler
module.exports.handler = (event, context) =>
  api.handleRequest(
    {
      method: event.httpMethod,
      path: event.path,
      query: event.queryStringParameters,
      body: event.body,
      headers: event.headers,
    },
    event,
    context,
  );

See full AWS SAM example

See full Serverless Framework example

Azure Function

module.exports = (context, req) =>
  api.handleRequest(
    {
      method: req.method,
      path: req.params.path,
      query: req.query,
      body: req.body,
      headers: req.headers,
    },
    context,
    req,
  );

See full Azure Function example

Hapi

import Hapi from '@hapi/hapi';

const server = new Hapi.Server({ host: '0.0.0.0', port: 9000 });
server.route({
  method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  path: '/{path*}',
  handler: (req, h) =>
    api.handleRequest(
      {
        method: req.method,
        path: req.path,
        body: req.payload,
        query: req.query,
        headers: req.headers,
      },
      req,
      h,
    ),
});
server.start();

See full Hapi example

Koa

import Koa from 'koa';
import bodyparser from 'koa-bodyparser';

const app = new Koa();

app.use(bodyparser());
app.use((ctx) =>
  api.handleRequest(
    ctx.request,
    ctx,
  ),
);
app.listen(9000);

See full Koa example

Registering Handlers for Operations

Handlers are registered for operationIdsfound in the OpenAPI definitions. You can register handlers as shown above with new OpenAPIBackend()constructor opts, or using the register()method.

async function getPetByIdHandler(c, req, res) {
  const id = c.request.params.id;
  const pet = await pets.getPetById(id);
  return res.status(200).json({ result: pet });
}
api.register('getPetById', getPetByIdHandler);
// or
api.register({
  getPetById: getPetByIdHandler,
});

Operation handlers are passed a special Context objectas the first argument, which contains the parsed request, thematched API operation and input validation results. The other arguments in the example above are Express-specifichandler arguments.

Request validation

The easiest way to enable request validation in your API is to register a validationFailhandler.

function validationFailHandler(c, req, res) {
  return res.status(400).json({ status: 400, err: c.validation.errors });
}
api.register('validationFail', validationFailHandler);

Once registered, this handler gets called if any JSON Schemas in either operation parameters (in: path, query, header,cookie) or requestPayload don't match the request.

The context object c gets a validation property with the validation result.

Response validation

OpenAPIBackend doesn't automatically perform response validation for your handlers, but you can register apostResponseHandlerto add a response validation step using validateResponse.

api.register({
  getPets: (c) => {
    // when a postResponseHandler is registered, your operation handlers' return value gets passed to context.response
    return [{ id: 1, name: 'Garfield' }];
  },
  postResponseHandler: (c, req, res) => {
    const valid = c.api.validateResponse(c.response, c.operation);
    if (valid.errors) {
      // response validation failed
      return res.status(502).json({ status: 502, err: valid.errors });
    }
    return res.status(200).json(c.response);
  },
});

It's also possible to validate the response headers using validateResponseHeaders.

api.register({
  getPets: (c) => {
    // when a postResponseHandler is registered, your operation handlers' return value gets passed to context.response
    return [{ id: 1, name: 'Garfield' }];
  },
  postResponseHandler: (c, req, res) => {
    const valid = c.api.validateResponseHeaders(res.headers, c.operation, {
      statusCode: res.statusCode,
      setMatchType: 'exact',
    });
    if (valid.errors) {
      // response validation failed
      return res.status(502).json({ status: 502, err: valid.errors });
    }
    return res.status(200).json(c.response);
  },
});

Auth / Security Handlers

If your OpenAPI definition contains Security Schemesyou can register security handlers to handle authorization for your API:

components:
  securitySchemes:
  - ApiKey:
      type: apiKey
      in: header
      name: x-api-key
security:
  - ApiKey: []
api.registerSecurityHandler('ApiKey', (c) => {
  const authorized = c.request.headers['x-api-key'] === 'SuperSecretPassword123';
  // truthy return values are interpreted as auth success
  // you can also add any auth information to the return value
  return authorized;
});

The authorization status and return values of each security handler can beaccessed via the Context Object

You can also register an unauthorizedHandlerto handle unauthorized requests.

api.register('unauthorizedHandler', (c, req, res) => {
  return res.status(401).json({ err: 'unauthorized' })
});

See examples:

Mocking API responses

Mocking APIs just got really easy with OpenAPI Backend! Register a notImplementedhandler and use mockResponseForOperation()to generate mock responses for operations with no custom handlers specified yet:

api.register('notImplemented', (c, req, res) => {
  const { status, mock } = c.api.mockResponseForOperation(c.operation.operationId);
  return res.status(status).json(mock);
});

OpenAPI Backend supports mocking responses using both OpenAPI example objects and JSON Schema:

paths:
  '/pets':
    get:
      operationId: getPets
      summary: List pets
      responses:
        200:
          $ref: '#/components/responses/PetListWithExample'
  '/pets/{id}':
    get:
      operationId: getPetById
      summary: Get pet by its id
      responses:
        200:
          $ref: '#/components/responses/PetResponseWithSchema'
components:
  responses:
    PetListWithExample:
      description: List of pets
      content:
        'application/json':
          example:
            - id: 1
              name: Garfield
            - id: 2
              name: Odie
    PetResponseWithSchema:
      description: A single pet
      content:
        'application/json':
          schema:
            type: object
            properties:
              id:
                type: integer
                minimum: 1
              name:
                type: string
                example: Garfield

The example above will yield:

api.mockResponseForOperation('getPets'); // => { status: 200, mock: [{ id: 1, name: 'Garfield' }, { id: 2, name: 'Odie' }]}
api.mockResponseForOperation('getPetById'); // => { status: 200, mock: { id: 1, name: 'Garfield' }}

See full Mock API example on Express

Contributing

OpenAPI Backend is Free and Open Source Software. Issues and pull requests are more than welcome!

  • 什么是API规范 API 是模块或者子系统之间交互的接口定义。好的系统架构离不开好的 API 设计,而一个设计不够完善的 API 则注定会导致系统的后续发展和维护非常困难。在关键环节制定明确的API规范有助于 Service 对内提高产品间互通的效率,对外提供一致的使用体验,也有助于更好地被集成。 对于API规范,比较知名的是 OpenAPI Specfication[1] 和 Google AP

  • 请注意,在实际使用中,需要使用 API 密钥,并根据 API 文档中的信息调用正确的端点和参数。 基础信息 Base URL: https://api.chatgpt.com/v1/ 认证方式: API Key 认证信息 您需要在 API 请求中包含您的 API 密钥以进行身份验证。 请求头(Headers): Authorization: Bearer YOUR_API_KEY 端点列表 客户服

  • Zuul 是提供动态路由,监控,弹性,安全等的边缘服务。Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门。Zuul 可以适当的对多个 Amazon Auto Scaling Groups 进行路由请求。 Zuul 包含多个组件: zuul-core  zuul-simple-webapp  zuul-netflix  zuul-netflix-webapp  ht

  • Nacos OpenAPI清单 new,2022-08-24,chenxizhan1995@163.com 清单 # 模块 接口名 方法 路径 备注 1 配置管理 获取配置 GET /nacos/v1/cs/configs tenant,dataId,group 2 配置管理 监听配置 POST /nacos/v1/cs/configs/listener 首部 Long-Pulling-Timeo

  • 所有的配置参数都对,一个个参数都调出来测试都没问题,但还是回调地址请求不通过,简直是一个大坑都是因为PHP缓冲区的问题,demo上面一般 echo ,return  输出的不行 PHP最好的做法是:ob_clean(); die($echoStr); 防止后面还有其它输出

 相关资料
  • OpenAI Gym is a toolkit for developing and comparing reinforcement learning algorithms. It makes no assumptions about the structure of your agent, and is compatible with any numerical computation libr

  • 可以通过 OpenAPI Generator,在给定 OpenAPI 规范(v2, v3)的情况下自动生成 API 客户端库、server stubs、文档以及配置。 目前支持以下语言/框架: Languages/Frameworks API clients ActionScript, Ada, Apex, Bash, C# (.net 2.0, 3.5 or later), C++ (cppre

  • OpenAPI-CodeGen Node.js-based codegen for OpenAPI documents. This project was initially a 24-hour hackathon. The local model adaptor code is entirely original and has been reverse-engineered from the

  • Directory of API definitions in OpenAPI(fka Swagger) 2.0 and 3.x formats. API access to collection: Go! - We also have an RSS Feed Our goal is to create the most comprehensive, standards-compliant and

  • OpenAPI Specification 的目标是为 REST API 定义一个标准的、与语言无关的接口,允许人和计算机在不访问源代码、文档或通过网络的情况下发现和理解服务的功能。 通过 OpenAPI 的正确定义,消费者可以用最简答的方式理解远程服务并与其交互,消除了调用服务时的猜测。 OpenAPI不需要重写现有的API。它不需要将任何软件绑定到服务,所描述的服务甚至可能不是您的。然而,它要