Efficiently Manage Your GraphQL API with API Gateway
Tags: webdev, graphql, programming, productivity
Published: 2023-03-22 07:32:24

[GraphQL](https://graphql.org/) 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](https://en.wikipedia.org/wiki/Representational_state_transfer), 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](https://apisix.apache.org/docs/apisix/terminology/api-gateway/) comes in.

One of the key features of modern API Gateways such as [Apache APISIX](https://apisix.apache.org/) 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](https://apisix.apache.org/docs/apisix/plugins/degraphql/) 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](https://static.apiseven.com/uploads/2023/03/20/h1qKgNBF_Manage%20Your%20GraphQL%20API%20with%20API%20Gateway%204.png)

## Why use DeGraphQL plugin?

[This plugin](https://apisix.apache.org/docs/apisix/plugins/degraphql/) is able to _transform APIs exposed by a GraphQL upstream (backend service) into a traditional REST endpoint_ by mapping URIs into [GraphQL queries](https://graphql.org/learn/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 through REST API 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 it 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](https://apisix.apache.org/plugins/).

## How to use DeGraphQL plugin (Demo)

With enough theoretical knowledge in mind, now we can jump into a practical demo of [DeGraphQL plugin](https://apisix.apache.org/docs/apisix/plugins/degraphql/). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nz4yey0e7py50kcyyn3v.png)

> You can also build your own GraphQL API using [StepZen](https://stepzen.com/getting-started) or [ApollographQL](https://www.apollographql.com/) 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:

```bash
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:

```bash
{
  "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](https://apisix.apache.org/docs/apisix/installation-guide/) on the Apache APISIX website to get started.

#### Prerequisites

- [Docker](https://docs.docker.com/get-docker/) is used to installing the containerized etcd and APISIX.
- [curl](https://curl.se/) is used to send requests to APISIX for validation. You can also use easy tools such as [Postman](https://www.postman.com/) to interact with the API.

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

```bash
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](https://apisix.apache.org/docs/apisix/admin-api/) that proxies requests to GraphQL API.

### Create an Upstream

Next, we will create an [Upstream](https://apisix.apache.org/docs/apisix/terminology/upstream/) object to register our [Countries GrapghQL API](https://countries.trevorblades.com/) in the API Gateway:

```bash
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](https://apisix.apache.org/docs/apisix/terminology/plugin-config/) object. We will use two transformation plugins [proxy-rewrite](https://apisix.apache.org/docs/apisix/plugins/proxy-rewrite/) and [degraphql](https://apisix.apache.org/docs/apisix/plugins/degraphql/) to rewrite the host and URI of the request and make a query to GraphQL API respectively.

```bash
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:

```bash
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:

```bash
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.

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

We will get response from APISIX:

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

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

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

### Response Transformation

With the help of Apisix's [response-rewrite](https://apisix.apache.org/docs/apisix/plugins/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.

```bash
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:

```json
{
  "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 making it a breeze to integrate into your existing API gateway, while it supports GraphQL-specific functionality ensuring that your API is performant, reliable, and scalable.

### Related resources

- [What is GraphQL?](https://api7.ai/blog/what-is-graphql).

- [Apache APISIX DeGraphQL Plugin](https://apisix.apache.org/docs/apisix/plugins/degraphql/)

### Recommended content

- [Why Is Apache APISIX the Best API Gateway?](https://api7.ai/blog/why-is-apache-apisix-the-best-api-gateway)

- [How to choose the right API Gateway](https://www.iambobur.com/post/how-to-choose-the-right-api-gateway).

### Community

🙋 [Join the Apache APISIX Community](https://apisix.apache.org/docs/general/join/)
🐦 [Follow us on Twitter](https://twitter.com/ApacheAPISIX)
📝 [Find us on Slack](https://join.slack.com/t/the-asf/shared_invite/zt-vlfbf7ch-HkbNHiU_uDlcH_RvaHv9gQ)
💁 [How to contribute page](https://apisix.apache.org/docs/general/how-to-contribute/)

### About the author

Visit my personal blog: [www.iambobur.com](https://www.iambobur.com/)