openapi-backend

repository·main·Indexed 20 days ago

https://github.com/openapistack/openapi-backend

A framework-agnostic middleware tool for building, validating, routing, authenticating, and mocking APIs using OpenAPI specifications without the need for code generation. Version 5.20.0.

Tokens
11.2K
Snippets
52
Records
56
Agent score
71%

What's inside openapi-backend

  1. How mockResponseForOperation() resolves data

    main

    The mockResponseForOperation(operationId) method resolves data based on your OpenAPI specification in the following priority:

    1. OpenAPI example objects: If the response content contains an example field, that object is returned.
    2. JSON Schema: If no example is present, it uses the schema definition to generate a mock object.

    Example OpenAPI structure supported:

    paths:
      '/pets':
        get:
          operationId: getPets
          responses:
            200:
              content:
                'application/json':
                  example:
                    - id: 1
                      name: Garfield
      '/pets/{id}':
        get:
          operationId: getPetById
          responses:
            200:
              content:
                'application/json':
                  schema:
                    type: object
                    properties:
                      id: { type: integer }
                      name: { type: string, example: Garfield }
  2. Perform Response Validation

    main

    OpenAPIBackend does not validate responses automatically. To enable response validation, register a postResponseHandler.

    When a postResponseHandler is registered, the return value of your operation handler is passed to context.response. You can then use api.validateResponse or api.validateResponseHeaders to check the validity of the response against the OpenAPI spec.

    api.register({
      getPets: (c) => {
        // Return value is passed to context.response
        return [{ id: 1, name: 'Garfield' }];
      },
      postResponseHandler: (c, req, res) => {
        // Validate the body
        const valid = c.api.validateResponse(c.response, c.operation);
        if (valid.errors) {
          return res.status(502).json({ status: 502, err: valid.errors });
        }
        
        // Or validate headers
        const validHeaders = c.api.validateResponseHeaders(res.headers, c.operation, {
          statusCode: res.statusCode,
          setMatchType: 'exact',
        });
        if (validHeaders.errors) {
          return res.status(502).json({ status: 502, err: validHeaders.errors });
        }
    
        return res.status(200).json(c.response);
      },
    });
  3. QuickStart the OpenAPI Backend Serverless AWS Example

    main

    To run the OpenAPI Backend example configured for the Serverless Framework on AWS, follow these steps:

    1. Install dependencies using npm install.
    2. Start the development server with npm run dev. The API will be available at http://localhost:9000.
    3. Test the running API using curl commands to verify the endpoints.
    npm install
    npm run dev
    
    # Test endpoints
    curl -i http://localhost:9000/pets
    curl -i http://localhost:9000/pets/1
  4. QuickStart: Run the OpenAPI Backend Azure Functions Example

    main

    This example demonstrates how to use openapi-backend within an Azure Functions environment. To run the local development server, ensure you have the Azure Functions Core Tools installed, then execute the following commands:

    1. Install dependencies: npm install
    2. Start the API: npm start

    Once running, the API is accessible at http://localhost:9000.

    npm install
    npm start
  5. QuickStart with OpenAPI Backend and AWS SAM

    main

    This example demonstrates how to use openapi-backend within an AWS SAM (Serverless Application Model) environment.

    Prerequisites

    Setup and Execution

    1. Install dependencies:
      npm install
    2. Start the local development environment:
      npm start
      The API will be available at http://localhost:3000.

    Testing the API

    You can verify the running API using curl against the pet endpoints:

    curl -i http://localhost:3000/pets
    curl -i http://localhost:3000/pets/1
    npm install
    npm start
    
    # Test endpoints
    curl -i http://localhost:3000/pets
    curl -i http://localhost:3000/pets/1
  6. QuickStart with OpenAPI Backend and Hapi

    main

    To run the OpenAPI Backend Hapi example project, install the dependencies and start the development server. Once running, the API will be available at http://localhost:9000.

    Setup Steps

    1. Install dependencies: npm install
    2. Start the development server: npm run dev

    Testing the API

    You can verify the running API using curl to access the /pets endpoints:

    npm install
    npm run dev
    
    # Test endpoints
    curl -i http://localhost:9000/pets
    curl -i http://localhost:9000/pets/1
  7. QuickStart with OpenAPI Backend and Express

    main

    To run the OpenAPI Backend Express example project, install the dependencies and start the development server. Once running, the API will be accessible at http://localhost:9000.

    Setup Steps

    1. Install dependencies: npm install
    2. Start the development server: npm run dev

    Testing the API

    You can verify the running API using curl to hit the /pets endpoints:

    npm install
    npm run dev
    
    # Test endpoints
    curl -i http://localhost:9000/pets
    curl -i http://localhost:9000/pets/1
  8. QuickStart: Deploy OpenAPI Backend with AWS CDK

    main

    This example demonstrates how to use openapi-backend within an AWS CDK infrastructure. To run this example, you must have NodeJS, NPM, AWS, and AWS CDK installed. If you wish to run tests or start the application locally, you also need AWS SAM CLI (>= v1.65) and Docker.

    Prerequisites

    1. AWS Authentication: Ensure you are authenticated with your AWS profile (e.g., via SSO).

      aws sso login --profile your-profile
    2. CDK Bootstrap: The CDK environment must be bootstrapped for your specific AWS account and region.

      AWS_PROFILE=your-profile npx cdk bootstrap aws://YOUR_ACCOUNT_ID/YOUR_DEFAULT_REGION

    Deployment

    Deploy the stack using the following command:

    AWS_PROFILE=your-profile npx cdk deploy

    After deployment, locate the OpenAPIBackendHttpApiEndpoint in the command output. This is your API Gateway URL.

    Testing the API

    Set the deployed URL as an environment variable to simplify testing:

    export CDK_OUTPUT_API_GW_URL=https://your-api-gateway-url.execute-api.region.amazonaws.com
    
    # Test endpoints
    curl -i "$CDK_OUTPUT_API_GW_URL/pets"
    curl -i "$CDK_OUTPUT_API_GW_URL/pets/1"
  9. Quick Start with OpenAPIBackend

    main

    To use openapi-backend, instantiate the OpenAPIBackend class with your OpenAPI definition (file path or object), register handlers for your operationIds, and call api.init().

    Handlers receive a special Context object (c) as the first argument, which contains parsed request data, the matched operation, and validation results. Subsequent arguments follow your framework's signature (e.g., Express's req and res).

    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();