Build a GraphQL API on 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');

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');

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/

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.

Reference:https://www.alibabacloud.com/blog/build-a-graphql-api-on-function-compute-and-api-gateway_594188?spm=a2c41.12311536.0.0

Written by

Follow me to keep abreast with the latest technology news, industry insights, and developer trends.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store