×
Community Blog Build a GraphQL API on Function Compute and API Gateway

Build a GraphQL API on Function Compute and API Gateway

This article shows you how you can easily integrate GraphQL with Alibaba Cloud Function Compute and API Gateway.

By Suenaga Ryota, Alibaba Cloud MVP

What Is GraphQL?

GraphQL is an open-source query language for APIs, originally developed by Facebook. GraphQL can be used in conjunction with Alibaba Cloud Function Compute and API Gateway. For more information, about GraphQL, visit the official GraphQL site. We will not go into the details of GraphQL as this article is meant to be a quick and simple tutorial.

We got a result by throwing POST request to one endpoint. The curl command below is an example to get messages.

$ curl -H "Content-Type: application/json" -X POST -d '
{
  "query": "{ messages { name body } }"
}
' http://xxxxxxxxxxxxxxxxxx-cn-shanghai.alicloudapi.com/

{"data":{"messages":[{"body":"Hello","name":"asmsuechan"},{"body":"World","name":"suechan"}]}}

Minimum Code for GraphQL to Work on Function Compute

I wrote the bare minimum GraphQL code and made it work on Function Compute.

I expected the combination of query and return value below:

Query: "{ hello }"
Return Value: { data: { hello: "world" } }

This sample below came from GraphQL's Official GitHub.

// index.js
const { hook } = require('fc-helper');
const {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString
} = require('graphql');

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      hello: {
        type: GraphQLString,
        resolve() {
          return 'world';
        }
      }
    }
  })
});

const query = '{ hello }';

module.exports.handler = (event, context, callback) => {
  graphql(schema, query).then((result) => {
    callback(null, { statusCode: 200, body: result });
  });
});

It's easy. Just execute graphql() in the handler function.

More Detailed API

Next, I made some improvements to the API. I expected a more complex combination of queries and return values below:

Query: "{ messages { name body } }"
Return value: {"data":{"messages":[{"body":"Hello","name":"asmsuechan"},{"body":"World","name":"suechan"}]}}

I defined a type named message to get plural message.

// index.js
const { hook } = require('fc-helper');
const {
  graphql,
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLList,
  GraphQLString
} = require('graphql');
const atob = require('atob');

const messages = [
  {
    name: 'asmsuechan',
    body: 'Hello'
  },
  {
    name: 'suechan',
    body: 'World'
  }
];

const schema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
      messages: {
        type: GraphQLList(
          new GraphQLObjectType({
            name: 'message',
            fields: {
              name: { type: GraphQLString },
              body: { type: GraphQLString },
            },
          }),
        ),
        resolve() {
          return messages;
        }
      }
    }
  })
});

module.exports.handler = (event, context, callback) => {
  const request = JSON.parse(event.toString('utf8'))
  const query = JSON.parse(atob(request["body"]))["query"]
  graphql(schema, query).then((result) => {
    callback(null, { statusCode: 200, body: result });
  });
};

To check whether this API works well, I executed curl.

$ curl -H "Content-Type: application/json" -X POST -d '
{ "query": "{ messages { name body } }"}
'http://xxxxxxxxxxxxxxxxxx-cn-shanghai.alicloudapi.com/

{"data":{"messages":[{"body":"Hello","name":"asmsuechan"},{"body":"World","name":"suechan"}]}}

Conclusion

I am very happy to be able to use GraphQL instead of REST API on Alibaba Cloud Function Compute and API Gateway because we can create complex APIs without using so many API Gateways.

However, I haven't tested this on a production environment. You may try this yourself by referring to my code repository of this article: https://github.com/asmsuechan/fc_graphql_api

Article originally published here.

1 1 1
Share on

Alibaba Clouder

2,605 posts | 747 followers

You may also like

Comments

Raja_KT March 1, 2019 at 8:21 am

Nice one. Would like to see the REST vs GraphQL :)

5326127221743842 November 14, 2019 at 10:51 am

Thank you for your response!

Alibaba Clouder

2,605 posts | 747 followers

Related Products

  • Function Compute

    Alibaba Cloud Function Compute is a fully-managed event-driven compute service. It allows you to focus on writing and uploading code without the need to manage infrastructure such as servers.

    Learn More
  • API Gateway

    API Gateway provides you with high-performance and high-availability API hosting services to deploy and release your APIs on Alibaba Cloud products.

    Learn More
  • OpenAPI Explorer

    OpenAPI Explorer allows you to call an API through its web interface or WebCLI, and view the entire process.

    Learn More
  • Database Gateway

    A tool product specially designed for remote access to private network databases

    Learn More