openapi2graph
v0.14.0
Published
Generates a GraphQL schema for a given OpenAPI Specification (OAS)
Downloads
13
Maintainers
Readme
OASGraph
Generates a GraphQL schema for a given OpenAPI Specification (OAS).
Note: To use OASGraph via the command line, refer to the oasgraph-cli
package.
Installation
OASGraph can be installed using:
npm i oasgraph
Note that GraphQL.js
is a peer dependency of OASGraph and must be installed separately (e.g., using npm i graphql
).
Usage
The basic way to use OASGraph is to pass an OpenAPI Specification (OAS; version 2.0 or 3.0.x) to the generateGraphQLSchema
function. The function returns a promise that resolves on an object containing the generated GraphQL schema as well as a report about possible issues when generating the schema:
const { createGraphQlSchema } = require('oasgraph')
// load or construct OAS (const oas = ...)
const { schema, report } = await createGraphQlSchema(oas)
Example of Serving the Generated GraphQL Schema
The schema generated by OASGraph can, for example, be served using Express.js and the GraphQL HTTP Server Middleware:
const express = require('express')
const graphqlHTTP = require('express-graphql')
const OASGraph = require('oasgraph')
async function main (oas) {
// generate schema:
const {schema, report} = await createGraphQLSchema(oas)
// server schema:
const app = express()
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}))
app.listen(3001)
}
main(oas) // oas loaded / constructed someplace else
Options
The createGraphQlSchema
function takes an optional options
object as a second argument:
createGraphQLSchema(oas, [options])
The options object can contain the following properties:
strict
(type:boolean
, default:false
): OASGraph generally tries to produce a working GraphQL schema for a given OAS if the strict mode is disabled. If OASGraph cannot fully translate a given OAS (e.g., because data schema definitions are incomplete or there are name collusions that cannot be resolved),createGraphQLSchema
will per default degrade gracefully and produce a partial GraphQL schema. OASGraph will log warnings (given logging is enabled). If thestrict
mode is enabled, however,createGraphQLSchema
will throw an error if it cannot create a GraphQL schema matching the given OAS perfectly.headers
(type:object
, default:{}
): Headers to be sent in every request to the API described by the given OAS. Parameters defined in the OpenAPI Specification to set these headers will be ignored by OASGraph.qs
(type:object
, default:{}
): Query parameters to be sent in every request to the API described by the given OAS. Parameters defined in the OpenAPI Specification to set these query parameters will be ignored by OASGraph.viewer
(type:boolean
, default:true
): The viewer object types (i.e.QueryViewer
andMutationViewer
) are artificial constructs that allow users to pass authentication credentials to OASGraph. Unfortunately, they are bulky and do not provide an accurate representation of the API. Depending on the API, it may be possible to send all credentials through the header option, so this option allows to disable OASGraph-generated viewer object types.tokenJSONpath
(type:string
, default:undefined
): Used to pass the JSONPath of the OAuth token in the GraphQL context. To see more details, click here.addSubOperations
(type:boolean
, default:false
): When true, OASGraph will nestGET
operations based on their path hierarchy in the given OAS. E.g., when the OAS contains two paths/users/{id}
and/users/{id}/friends
, OASGraph will makefriends
queryable from withinuser
. Note: This may cause problems when resolving GraphQL types in certain contexts, where the required variables are not available.fillEmptyResponses
(type:boolean
, default:false
): OASGraph, by default, will only wrap operations that have a response schema and operations that do not have a response schema will be ignored. The reason is that all GraphQL objects must have a data structure and in these cases, where the OAS does not define a response schema, the data structure cannot be safely assumed. As a result, it is recommended that the OAS should be modified to include a response schema. However, under certain circumstances, some operations should not in fact have a response schema. One circumstance is HTTP status code 204, in which no content should be returned. The optionfillEmptyResponses
will allow OASGraph to wrap these operations by assigning these operations a nullable data structure. Although this data structure is meaningless, the operation will appear in the schema.
Consider this example of passing options:
OASGraph.createGraphQLSchema(oas, {
headers: {
authorization: 'asfl3032lkj2' // send authorization header in every request
'x-origin': 'GraphQL' // send header to identify requests made via GraphQL
},
qs: {
limit: 30 // send limit query string in every request
},
addSubOperations: false
})
Authentication
Per default, OASGraph will wrap API requests that need authentication in corresponding viewers
, which allow the user to pass required credentials. OASGraph currently supports viewers for basic authentication and API keys. For example, a query using an API key viewer is:
{
viewerApiKey (apiKey: "api_key_here") {
... // query for authenticated data here
}
}
OASGraph uses dedicated viewers for mutations. For example, a mutation using a basic authentication viewer is:
mutation {
mutationViewerBasic (username: "user", password: "secret") {
... // mutate authenticated data here
}
}
OASGraph further provides anyAuth
viewers (for queries and mutations), which allow the user to simultaneously provide information for multiple authentication mechanisms. AnyAuth viewers allow OASGraph to resolve nested queries and mutations that encompass API requests with different authentication mechanisms. For example, consider the following query:
{
viewerAnyAuth (
exampleApiKeyProtocol: {apiKey: "a1p2i3k4e5y"}
exampleBasicProtocol: {
username: "erik"
password: "secret"
}
) {
patentWithId (patentId: "test") { // requires "exampleApiKeyProtocol"
patentId
inventor { // requires "exampleBasicProtocol"
name
}
}
}
}
Authorization
Because OASGraph is a library, it cannot make the callbacks that OAuth requires by itself. Instead, the user must take care of the callback. After the user has obtained the OAuth token from the callback, simply pass the token, specifically the path of the token, to OASGraph through the tokenJSONpath
option.
To see an example of how this would work, click here!
Logging
OASGraph provides multiple levels of logging, which can be controlled by a DEBUG
environment variable. You can enable these levels using:
DEBUG=level_1,level_2 node app-using-oasgraph.js
The following logging levels are supported:
preprocessing
: Logs information about preprocessing the OAS to GraphQL.translation
: Logs information about translating an OAS to GraphQL.http
: Logs information about the HTTP requests made to the API.
Testing
To test OASGraph, run:
npm test
This command will temporarily start and later shut down an example REST(-like) API.