Efficiently Manage Your GraphQL API with API Gateway

Bobur Umurzokov

Bobur Umurzokov

March 21, 2023

Technology

GraphQL is a powerful query language for APIs that allows developers to define the structure of the data they need from the server, and the server responds with only that data. This makes it much more efficient and flexible than traditional REST APIs, which often require multiple requests to retrieve the same data. However, managing GraphQL APIs can be complex and time-consuming, especially at scale. This is where an API Gateway comes in.

One of the key features of modern API Gateways such as Apache APISIX is its support for GraphQL APIs. APISIX makes it easy to manage and scale GraphQL APIs using its flexible configuration system and powerful plugins. One such plugin is the degrapghql plugin, which allows us to convert the GraphQL API into a REST API. In this post, we will explore this feature with an example.

Learning objectives

You will learn and find out answers to the following questions throughout the article:

  • What is the DeGraphQL plugin?
  • What are the use cases and features of the DeGraphQL plugin?
  • How to use the DeGraphQL plugin.
  • How to transform REST to GraphQL?
  • How to manage GraphQL API traffic?

Manage Your GraphQL API with API Gateway

Why use DeGraphQL plugin?

This plugin is able to transform APIs exposed by a GraphQL upstream (backend service) into a traditional REST endpoint by mapping URIs into GraphQL queries. Calling REST APIs from a typical client opens the benefits of GraphQL for more people, consider the following use-cases:

Use-case 1: Your existing customers are used to consuming REST APIs and are not too familiar with how to write GraphQL queries. In order to keep things simple for them, you can use Apache APISIX API Gateway to convert GraphQL API to a REST API.

Use-case 2: You are in a front-end development team that wants to try existing GraphQL API functionalities without asking for the back-end team to implement a new GraphQL server.

Use-case 3: You have no access to change the backend because it's an existing set of GraphQL APIs, potentially managed by a 3rd party.

Use-case 4: You have an existing REST API infrastructure, but you're looking to evaluate whether GraphQL can work for your needs.

Use-case 5: You have a large codebase, and the GraphQL migration is happening on the backend, but you want to use GraphQL now without waiting.

Use-case 6: You have multiple microservices and they use the combination of both approaches. You want to enable smooth communication between them.

What are the DeGraphQL plugin features?

DeGraphQL plugin provides a number of useful features that make it easy to configure and manage your GraphQL API, including:

Request Validation: It can validate incoming GraphQL requests to ensure they meet certain criteria. This can include checking the structure of the query, enforcing input type constraints, and more. By validating requests, you can ensure that your API is always receiving valid and well-formed requests.

Query Parsing: It can also parse GraphQL queries, allowing you to extract specific information from the query and use it to inform your API's behavior. This can include things like selecting the appropriate backend service based on the requested data, or modifying the response based on certain query parameters.

Response Transformation: Finally, it can transform GraphQL responses before they are returned to the client. This can be useful for things like normalizing data structures, removing sensitive information, or adding additional data to the response.

With this capability, Apache APISIX not only makes easy to use REST and GraphQL together but you can also define rate limits, enforce authentication and authorization, block clients that attempt to misuse an API, and ensure APIs work seamlessly as they are updated with help of other built-in plugins.

How to use DeGraphQL plugin (Demo)

With enough theoretical knowledge in mind, now we can jump into a practical demo of DeGraphQL plugin. DeGraphQL needs a GraphQL endpoint to query. As an example, we are going to use one of the free public GraphQL APIs that retrieve information about countries, continents, and languages https://countries.trevorblades.com/.

If you navigate to the above Countries API link, it will open a playground where you can write some queries against GraphQL API on the UI.

Querying GraphQL API

You can also build your own GraphQL API using StepZen or ApollographQL provided GraphQL studios that helps you build and deploy your own GraphQL API by combining prebuilt APIs such as Accuweather, Airtable, GitHub, Twitter, Trello, and more. For example, you compose two Accuteweather and Countries APIs together to collect the weather information provided by a country/city name and put APISIX at the front to query the API from REST.

Now our task is to transform the above query definition to a simple REST call and send it as JSON data. As an outcome, the Apache APISIX API Gateway exposes the REST endpoint and should be able to route all requests to the GraphQL API.

For example, all REST requests to API Gateway /country-info URI path with an underlining query by a country code should be converted and passed to GraphQL countries API https://countries.trevorblades.com/graphql.

An example curl command that looks something like this:

curl -i http://127.0.0.1:9080/country-info  -X POST -d \
'{
   "code": "EE"
}'

And we should get a response from the API as follows:

{
  "data": {
    "country": {
      "code": "EE",
      "capital": "Tallinn",
      "currency": "EUR",
      "languages": [
        {
          "name": "Estonian"
        }
      ]
    }
  }
}

In the next sections, we will learn how to achieve this step-by-step.

Let’s get Apache APISIX up and running

Before you can use the degrapghql plugin, you'll need to install Apache APISIX. You can follow the installation instructions on the Apache APISIX website to get started.

Prerequisites

  • Docker is used to install the containerized etcd and APISIX.
  • curl is used to send requests to APISIX for validation. You can also use easy tools such as Postman to interact with the API.

APISIX can be easily installed and started with the following quickstart script:

curl -sL https://run.api7.ai/apisix/quickstart | sh

This will create two Docker containers – a etcd to store configuration and APISIX Gateway itself. Once you see the “✔ APISIX is ready!” message, we can configure an upstream, plugin and route via APISIX's Admin API that proxies requests to GraphQL API.

Create an Upstream

Next, we will create an Upstream object to register our Countries GrapghQL API in the API Gateway:

curl "http://127.0.0.1:9180/apisix/admin/upstreams/1" -X PUT -d '
{
  "name": "GraphQL API upstream",
  "desc": "Register Countries GraphQL API as the upstream",
  "type": "roundrobin",
  "scheme": "https",
  "nodes": {
    "countries.trevorblades.com": 1
  }
}'

Create a Plugin Config

Next, a set up new plugin config object. We will use two transformation plugins proxy-rewrite and degraphql to rewrite the host and URI of the request and make a query to GraphQL API respectively.

curl http://127.0.0.1:9180/apisix/admin/plugin_configs/1 -X PUT -d '
{
   "plugins":{
      "proxy-rewrite":{
         "uri":"/graphql",
         "host":"countries.trevorblades.com"
      },
      "degraphql":{
         "query":"query Country($code: ID!) {
                country(code: $code) {
                    code
                    capital
                    currency
                    languages {
                        name
                    }
                }  
          }",
         "variables":[
            "code"
         ]
      }
   }
}'

In the above DeGraphQL plugin configuration, we set two attributes such as query and variables. GraphQL query variables can be defined on the Post request body or URIs in a REST call.

The query we’re executing, in this case, looks like the following and you can replace it with your own:

query ($code: ID!) {
  country(code: $code) {
    code
    capital
    currency
    languages {
      name
    }
  }
}

Create a Route with DeGraphQL plugin

This step involves setting up a new route that uses the plugin config, and configuring the route to work with the upstream (by referencing their IDs) we created in the previous steps:

curl -i http://127.0.0.1:9180/apisix/admin/routes/1 -X PUT -d '
{
   "name":"GraphQL API route",
   "desc":"Create a new route in APISIX for the Countries GraphQL API",
   "uri":"/country-info",
   "upstream_id":"1",
   "plugin_config_id":1
}'

Test DeGraphQL plugin activation

Now let’s test this new setup with the following curl command.

curl -i http://127.0.0.1:9080/country-info  -X POST -d \
'{
   "code": "EE"
}'

We will get response from APISIX:

{
  "data": {
    "country": {
      "code": "EE",
      "capital": "Tallinn",
      "currency": "EUR",
      "languages": [
        {
          "name": "Estonian"
        }
      ]
    }
  }
}

The same code variable can also be provided as GET arguments:

curl -i http://127.0.0.1:9080/country-info?code=EE

Response Transformation

With the help of Apisix's response-rewrite plugin, it is possible to transform GraphQL responses before they are returned to the client. Let's use this plugin to remove the currency key and value from the response JSON to show only everything else. To do so, we need to add the response-rewrite plugin to the existing plugin configuration.

curl http://127.0.0.1:9180/apisix/admin/plugin_configs/1 -X PATCH -d '
{
  "plugins":{
   "response-rewrite": {
      "filters":[
        {
          "regex":"(?:\"currency\":\")(.*?)(?:\")",
          "scope":"once",
          "replace":""
        }
      ],
      "vars":[
        [
          "status",
          "==",
          200
        ]
      ]
   }
  }
}'

After this plugin is installed, you can make a request to /country-info once again and see the transformed response:

{
  "data": {
    "country": {
      "code": "EE",
      "capital": "Tallinn",
      "languages": [
        {
          "name": "Estonian"
        }
      ]
    }
  }
}

Summary

Overall, the DeGraphQL plugin is an essential tool for any developer building a GraphQL API with APISIX. It has powerful features and easy-to-use configuration make it a breeze to integrate into your existing API gateway, while it supports for GraphQL-specific functionality ensures that your API is performant, reliable, and scalable.

Tags:
API Gateway ConceptGraphQLPlugin