Overview

TheOpenAPI-to-GraphQL modulecreates a GraphQL wrapper for existing REST APIs which are described by theOpenAPI specification. This tutorial shows how to expose GraphQL APIs in anexisting LoopBack application.

Prerequisite

Make sure you have a running LoopBack 4 application. In this tutorial, we’ll usethe todo example. You can create this application by running the commandbelow:

  1. lb4 example todo

Install OpenAPI-to-GraphQL and Required Dependencies

From your LoopBack application, run the following command to installOpenAPI-to-GraphQL and the required dependencies:

  1. npm i --save openapi-to-graphql-cli

Start the GraphQL Server

Make sure your LoopBack application is running by going tohttp://localhost:3000/openapi.json. If not, you can start it by running thenpm start command.

Now we will use the OpenAPI-to-GraphQL CLI to set up a GraphQL HTTP Serverbacked by express on port 3001. Specifying the OpenAPI spec generated by thetodo-application as the parameter, start up the server by running the followingcommand:

  1. npx openapi-to-graphql http://localhost:3000/openapi.json

Haven’t heard about npx yet? It’s a cool helper provided by npm andavailable out of the box since Node.js 8.x. Learn more in their announcementblog post:Introducing npx: an npm package runner

That’s it! You’re now ready to try out some tests and requests in the browser athttp://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. Seeissue #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:
  1. query{
  2. todos {
  3. id
  4. title
  5. desc
  6. }
  7. }

The expected output looks like this:

  1. {
  2. "data": {
  3. "todos": [
  4. {
  5. "id": 1,
  6. "title": "Take over the galaxy",
  7. "desc": "MWAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA"
  8. },
  9. {
  10. "id": 2,
  11. "title": "destroy alderaan",
  12. "desc": "Make sure there are no survivors left!"
  13. },
  14. {
  15. "id": 3,
  16. "title": "play space invaders",
  17. "desc": "Become the very best!"
  18. },
  19. {"id": 4, "title": "crush rebel scum", "desc": "Every.Last.One."}
  20. ]
  21. }
  22. }
  • Create a to-do instance and retrieve its ID and title in the response objectusing the following mutation command:
  1. mutation {
  2. todoControllerCreateTodo(todoInput: {
  3. title: "Take over the universe"
  4. }) {
  5. id
  6. title
  7. }
  8. }

The expected output looks like this:

  1. {
  2. "data": {
  3. "todoControllerCreateTodo": {
  4. "id": 5,
  5. "title": "Take over the universe"
  6. }
  7. }
  8. }