Wrap a REST API endpoint with GraphQL in Node.js
Follow this tutorial to wrap a REST API endpoint with a GraphQL wrapper to make it accessible via a dedicated GraphQL API.
In this tutorial we will use a standalone Apollo server, which is an easy-to-use option for setting up a GraphQL server without any additional configuration. For the REST API endpoint we will use the City Search API.
The goal of this tutorial is to create a GraphQL API, which will only use the keyword
parameter for the query and return only the name
parameter in the response.
Pre-requisites
Before you begin, you need to:
- Register your application with Amadeus for Developers as described in Making your first API call.
- Have Node.js installed on your machine.
Initialize a new Node.js project
- Open your terminal and create a new directory for this project:
- Navigate to the directory and run the following command to initialize a new Node.js project:
Install required dependencies
Install apollo-server
, graphql
, and node-fetch
packages by running:
Define GraphQL schema
Create a schema.graphql
file with the necessary types and queries. In this tutorial, we are only using the keyword
parameter to query the City Search API and we are only interested in the name
parameters that this query returns in the response data. For this reason, our schema.graphql
will look as follows:
Create a data fetching function
Information
The node-fetch
package is an ECMAScript module (ESM), so we will use .mjs
extensions and ECMAScript module syntax in these examples.
Create a fetchData.mjs
file and define a function that fetches data from the REST endpoint using node-fetch
:
In the above example we are outputting logs to the console for easier troubleshooting.
Implement GraphQL resolvers
Create a resolvers.mjs
file and implement the resolver functions for the queries:
Set up the Apollo server
Create the main file index.mjs
that sets up the Apollo server with the schema and resolvers:
Run the server
Open the terminal and run:
Query the GraphQL API
Information
Before running the query, make sure to obtain the token as described in our Authorization guide.
Now that we have the server running, we can send requests to it. The most straightforward method to do this is by using curl
. To query this API by the keyword
"Paris":
If your token is valid, the above command will return a list of city names that contain the word Paris
.