Over the past two decades REST APIs have emerged as a lightweight and flexible standard for enterprise data and backends get exposed to external, partner, and internal applications. Google Cloud’s Apigee is a leader in API Management, allowing users to manage REST APIs — define rate limits, enforce authentication and authorization, block clients that attempt to misuse an API, and ensure APIs work seamlessly as they are updated.
GraphQL is fast emerging as a paradigm for building developer-friendly and flexible APIs. It supports application developers requesting exactly the data they want from the backend data sources. Now with both REST and GraphQL as powerful API options, API providers face the challenge of building and managing this next generation of APIs. With this launch, Apigee makes it easy to use REST and GraphQL together. So developers don’t have to choose – adding GraphQL to your stack and leveraging existing investments in REST are both possible.
Apigee has added a new GraphQL policy to its rich suite of policies that let you control traffic, enhance performance, and enforce security without requiring you to write any code or modify any backend services. By adding the GraphQL policy into a proxy created in Apigee, a developer can validate that a GraphQL query and response conforms to a specific schema, and then can chain this policy in their standard Apigee proxy pre-flow to perform other validations and management functions against that backend API.
Apigee partners with StepZen to deliver these GraphQL capabilities. StepZen is an enterprise GraphQL provider, built on a foundation of low-code building blocks and connectors that speed up API development. In this blog, using a project you can clone from GitHub, which includes a GraphQL API built on StepZen, we’ll demonstrate how the policy works.
The high-level architecture looks like this:
What does our scenario do?
Our scenario is eCommerce personalization. A single GraphQL endpoint joins multiple APIs and is proxied through Apigee. Imagine an eCommerce experience that returns the city of the user and the cost, in the user’s local currency, of 3 US Dollars (USD) worth of goods. In just a few steps, you can query a single GraphQL endpoint, which joins multiple APIs. The GraphQL endpoint is protected by Apigee GraphQL policies.
How does Apigee Help
Apigee checks that the query conforms to the schema, ensures that the API key is valid, and collects analytics on the GraphQL call. Using Apigee’s API Product and GraphQL support, you can add a quota or even restrict access to certain GraphQL operations.
This simple setup validates against a single GraphQL schema. Furthermore, by leveraging Apigee’s support for flows, it is possible to have different versions of the schema available to different users. We can block requests for schemas outright while still allowing queries. Finally, we can publish access to the GraphQL endpoint in a developer portal enabling developers who consume APIs in a self-service fashion to subscribe and fetch their own unique credentials to access the new endpoint.
How does StepZen Help
StepZen executes the GraphQL call against the backends. Specifically, StepZen
Calls api.ip-api.com to get the city, country, and currency of the user based on IP address.
Uses the currency information from the first call to fetch the cost of a specified amount and currency worth of goods from the currency exchange API – api.frankfurter.com – using the current exchange rate.
Here’s an example GraphQL request and response that illustrates the scenario:
The query above retrieves both location information and currency information in a single request. Two REST APIs are called to generate the appropriate response. The StepZen schema adds a “priceInCountry” field to the location response, using a currency conversion API. Developers don’t need to worry about combining those APIs themselves, and they can choose which fields they want to retrieve and therefore shape the response to suit their needs.
Because both StepZen and Apigee have management APIs, you can automate the process of creating Apigee proxies for StepZen endpoints. And we’ve created an open source utility that does this for you! The utility provisions an account with StepZen if you do not have one. It deploys StepZen schemas and automatically builds Apigee proxies for them. The proxies are configured to require an API key to call them, and they automatically verify the GraphQL request against the StepZen schema.
Let’s get your environment up and running
Make sure that your account has sufficient privileges in Apigee to create and deploy: proxies, API Products, developers, apps, and property sets.
git clone [email protected]:apigee/stepzen.git
Change into the directory where you just cloned the repository, and run the following command:
./apizenSetup -o <your_org> -e <your_env> -t $(gcloud auth print-access-token) -i $(gcloud auth print-identity-token) -z
Though the script can take a number of optional parameters (explained in the README in the repo) by default you simply need to specify only:
-o <your organization/project name for your apigee setup>
-e <your environment name>
-t <a gcloud token with access to deploy and create needed apigee artifacts>
-i <a gcloud generated identity token>
StepZen uses this to generate a single, but unique StepZen account.
This is optional but if supplied the script will output your StepZen credentials. Useful if you’d like to use StepZen tooling later.
The script runs through a number of steps and outputs progress along the way:
Calls a StepZen endpoint to fetch details of your StepZen account
Creates or updates an Apigee PropertySet to store your StepZen credentials
Deploys an Apigee API Proxy that’s preconfigured with your StepZen account as a southbound target (relies on the property set configured above)
Create or Update Developer, API Product, and App with credentials to secure the endpoint
When the script has completed it displays an example curl command (see below) and shows the API Key created during the setup.
If you’ve provided the options `-z` options, as suggested above, the script outputs your StepZen account, admin key, and API key. (Note those down somewhere, and keep them safe from leaking.) You may save these details as YAML (they’re outputted as YAML in fact) to be used later with the StepZen tooling.
Testing the Endpoint
After the script completes you are shown an example curl command that looks something like this:
This curl command is referencing a file named `gql-query.json` that contains the same GraphQL query listed above in the example. Running this curl command yields precisely the same output listed above as well. Feel free to update the query in that file or copy it and create your own query files.
Add Google Maps to the API
For extra credit, let’s add Google Maps to this API. Now our eCommerce app can show the user the closest physical store where they can pick up an order that was made online (and decide whether it is easier for them to get delivery or pickup).
1. You’ll need an API key to call the Google Maps API from StepZen. Get one by following the instructions here: Getting started with Google Maps Platform
2. We have a sample schema prepared for you in the repository. StepZen Maps Sample – In this folder rename the file config.yaml.sample to config.yaml
3. Edit the config.yaml file to replace <apikey> with your key.
4. Run the script with the new StepZen schema. The script should find and reuse the StepZen account which was created the previous time.
5. Now let’s test this new setup with your curl command like you did before.
This time we will point to a GraphQL query stored in the `stepzen-maps-example` directory. So your new curl command looks something like this (Update the apikey and hostname for your own endpoint of course):
The query we’re executing in this case looks like the following:
What did this do?
The query looks for the nearest Target location relative to the Lat/Long for whatever IP is returned by the initial location query for Google DNS.
This is then passed down to the embedded `findNearby` as lat,lon resolved from that initial lookup. StepZen then uses the Google Maps API and key that we provided to StepZen when we configured our schema.
Combining this with the ability to query for api-ip-api.com we can enhance our experience and get the closest physical store that is a Target store in a single GraphQL query. (For a minute assume that is where the pickup experience is, but feel free to try other stores.)
See the following resources for more information about Apigee policies and building and running a StepZen GraphQL endpoint.
Apigee announcement for GraphQL Support – How to manage GraphQL APIs in Apigee
Apigee GraphQL policy – Using GraphQL | Apigee X
Getting started with StepZen – https://stepzen.com/docs/quick-start
Designing a GraphQL Schema https://stepzen.com/docs/design-a-graphql-schema
Cloud BlogRead More