Git Product home page Git Product logo

swagger-to-graphql's Introduction

Build Status

Swagger-to-GraphQL

Swagger-to-GraphQL converts your existing Swagger schema to an executable GraphQL schema where resolvers perform HTTP calls to certain real endpoints. It allows you to move your API to GraphQL with nearly zero effort and maintain both REST and GraphQL APIs. Our CLI tool also allows you get the GraphQL schema in Schema Definition Language.

Try it online! You can paste in the url to your own Swagger schema. There are also public OpenAPI schemas available in the APIs.guru OpenAPI directory.

Features

  • Swagger (OpenAPI 2) and OpenAPI 3 support
  • Bring you own HTTP client
  • Typescript types included
  • Runs in the browser
  • Formdata request body
  • Custom request headers

Usage

Basic server

This library will fetch your swagger schema, convert it to a GraphQL schema and convert GraphQL parameters to REST parameters. From there you are control of making the actual REST call. This means you can reuse your existing HTTP client, use existing authentication schemes and override any part of the REST call. You can override the REST host, proxy incoming request headers along to your REST backend, add caching etc.

import express, { Request } from 'express';
import graphqlHTTP from 'express-graphql';
import { createSchema, CallBackendArguments } from 'swagger-to-graphql';

const app = express();

// Define your own http client here
async function callBackend({
  context,
  requestOptions,
}: CallBackendArguments<Request>) {
  return 'Not implemented';
}

createSchema({
  swaggerSchema: `./petstore.yaml`,
  callBackend,
})
  .then(schema => {
    app.use(
      '/graphql',
      graphqlHTTP(() => {
        return {
          schema,
          graphiql: true,
        };
      }),
    );

    app.listen(3009, 'localhost', () => {
      console.info('http://localhost:3009/graphql');
    });
  })
  .catch(e => {
    console.log(e);
  });

Constructor (graphQLSchema) arguments:

export interface Options<TContext> {
  swaggerSchema: string | JSONSchema;
  callBackend: (args: CallBackendArguments<TContext>) => Promise<any>;
}
  • swaggerUrl (string) is a path or URL to your swagger schema file. required
  • callBackend (async function) is called with all parameters needed to make a REST call as well as the GraphQL context.

CLI usage

You can use the library just to convert schemas without actually running server

npx swagger-to-graphql --swagger-schema=/path/to/swagger_schema.json > ./types.graphql

Apollo federation support can be added by using graphql-transform-federation. You can extend your swagger-to-graphql schema with other federated schemas or the other way around. See the demo with a transformed schema for a working example.

Defining your HTTP client

This repository has:

To get started install node-fetch and copy the node-fetch example into your server.

npm install node-fetch --save

Implementing your own HTTP client

There a unit test for our HTTP client example, it might be useful when implementing your own client as well.

The function callBackend is called with 2 parameters:

  • context is your GraphQL context. For express-graphql this is the incoming request object by default. Read more. Use this if you want to proxy headers like authorization. For example const authorizationHeader = context.get('authorization').
  • requestOptions includes everything you need to make a REST call.
export interface CallBackendArguments<TContext> {
  context: TContext;
  requestOptions: RequestOptions;
}

RequestOptions

export interface RequestOptions {
  baseUrl?: string;
  path: string;
  method: string;
  headers?: {
    [key: string]: string;
  };
  query?: {
    [key: string]: string | string[];
  };
  body?: any;
  bodyType: 'json' | 'formData';
}
  • baseUrl like defined in your swagger schema: http://my-backend/v2
  • path the next part of the url: /widgets
  • method HTTP verb: get
  • headers HTTP headers which are filled using GraphQL parameters: { api_key: 'xxxx-xxxx' }. Note these are not the http headers sent to the GraphQL server itself. Those will be on the context parameter
  • query Query parameters for this calls: { id: 123 }. Note this can be an array. You can find some examples on how to deal with arrays in query parameters in the qs documentation.
  • body the request payload to send with this REST call.
  • bodyType how to encode your request payload. When the bodyType is formData the request should be URL encoded form data. Ensure your HTTP client sends the right Content-Type headers.

Resources

swagger-to-graphql's People

Contributors

0xr avatar raxpost avatar ofersadgat avatar marla-singer avatar tiberiuzuld avatar thejibz avatar kamilchm avatar sibelius avatar artomal avatar kbrandwijk avatar kirill-konshin avatar cheggil avatar puneetar avatar sartaj avatar saumitrab avatar stvvt avatar swcho avatar timsusa avatar wtgtybhertgeghgtwtg avatar zacanger avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.