Note:
The OpenAPI-to-GraphQL module is a general wrapper for existing OpenAPI REST APIs. For first-class GraphQL support, see @loopback/graphql
Overview
The OpenAPI-to-GraphQL module creates a GraphQL wrapper for existing REST APIs which are described by the OpenAPI specification. This tutorial shows how to expose GraphQL APIs in an existing LoopBack application.
Prerequisite
Make sure you have a running LoopBack 4 application. In this tutorial, we’ll use
the todo
example. You can create this application by running the command
below:
lb4 example todo
Install OpenAPI-to-GraphQL and Required Dependencies
From your LoopBack application, run the following command to install OpenAPI-to-GraphQL and the required dependencies:
npm i --save openapi-to-graphql-cli
Start the GraphQL Server
Make sure your LoopBack application is running by going to
http://localhost:3000/openapi.json
. If not, you can start it by running the
npm start
command.
Now we will use the OpenAPI-to-GraphQL CLI to set up a GraphQL HTTP Server backed by express on port 3001. Specifying the OpenAPI spec generated by the todo-application as the parameter, start up the server by running the following command:
npx openapi-to-graphql-cli --port=3001 http://localhost:3000/openapi.json
Haven’t heard about npx
yet? It’s a cool helper provided by npm
and
available out of the box since Node.js 8.x. Learn more in their announcement
blog post:
Introducing npx: an npm package runner
That’s it! You’re now ready to try out some tests and requests in the browser at http://localhost:3001/graphql.
Note:
We are looking into ways how to expose the GraphQL endpoint alongside the main REST API, on the same HTTP host and port. See issue #1905.
Try Out the GraphQL APIs
Here are some examples of the query
and mutation
calls:
-
To get all the to-do instances, run this query command:
query{ todos { id title desc } }
The expected output looks like this:
{ "data": { "todos": [ { "id": 1, "title": "Take over the galaxy", "desc": "MWAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA" }, { "id": 2, "title": "destroy alderaan", "desc": "Make sure there are no survivors left!" }, { "id": 3, "title": "play space invaders", "desc": "Become the very best!" }, {"id": 4, "title": "crush rebel scum", "desc": "Every.Last.One."} ] } }
-
Create a to-do instance and retrieve its ID and title in the response object using the following mutation command:
mutation { todoControllerCreate(newTodoInput: { title: "Take over the universe" }) { id title } }
The expected output looks like this:
{ "data": { "todoControllerCreate": { "id": 5, "title": "Take over the universe" } } }