What Is GraphQL?

GraphQL is a query language and server-side runtime for application programming interfaces (APIs) that gives API clients exactly the data they requested. As an alternative to REST, GraphQL allows developers to make requests to fetch data from multiple data sources with a single API call. GraphQL is designed to make APIs fast, flexible, and developer-friendly.

GraphQL gives API maintainers the flexibility to add or discard fields without affecting existing queries. Developers can build APIs the way they want, and the GraphQL specification ensures that APIs behave predictably for clients. GraphQL can also be deployed to an integrated development environment (IDE) called GraphiQL.

How Does GraphQL Work?

GraphQL is a development architecture style for building APIs using HTTP. Somewhat similar to REST and SOAP, GraphQL uses HTTP POST to send queries through the body of an HTTP request or its query parameters. 

Query language

The “QL” in GraphQL stands for “query language” – GraphQL provides a reliable query layer for the API, and an endpoint that developers can use to make requests. This query language allows developers to query the underlying dataset, and provides control over the structure of the GraphQL API response.

GraphQL provides broad access to many schema objects and properties, enabling a more powerful, flexible way to present digital resources through web APIs.

API endpoint

Instead of designing a separate API route for every underlying resource, GraphQL provides one URL from which you can query the required data like an API client would. Like Structured Query Language (SQL), GraphQL provides a formal language for constructing data requests, while defining the structure of the returned data. 

As with any other web API style or protocol, you can make requests to the GraphQL API through the API’s endpoint URL:

http://example.com/graphql

Submit queries using GET or POST

When you use GraphQL, you can send queries using HTTP POST or HTTP GET. When sending a query using HTTP POST, the method body looks like this:

{
 __type(name: “Address”) {
  name
 }
}

Here is another query intended to search the data and define its structure. It instructs the API to return the names of all the entries called “Address”:

{
"data": {
 "__type": {
  "name": "Address"
  }
 }
}

Standardized API protocol

GraphQL provides  API providers a standardized method for deploying APIs on top of databases, giving API consumers powerful query capabilities using a common web infrastructure. GraphQL uses the minimal possible capabilities from the HTTP protocol, and invests heavily in standardizing message formats instead of leveraging what already exists in HTTP. 

GraphQL makes it possible to access content and data across heterogeneous systems, providing developers with many familiar database features on the backend, and making mobile, web, single-page applications faster to develop.

GraphQL vs. REST

Facebook developed GraphQL to simplify REST endpoints. Instead of multiple endpoints disconnecting from small amounts of data, GraphQL has one endpoint that inputs complex queries and outputs only relevant information.

By contrast, REST operates the API as a series of to-do lists. Each query is independent. GraphQL allows the API consumer to specify the desired result, and only then carries out API operations. It then performs all operations required to deliver the data the consumer requested.

While REST has become the standard tool for developing web APIs, it has proven to be too inflexible to update quickly, and often returns too much or too little data to API consumers, causing operational and networking problems. GraphQL not only addresses these inefficiencies, but also provides a simpler and easier-to-use interface.

Enabling GraphQL with Solo Gloo Gateway

The Gloo GraphQL module embeds a GraphQL server natively into Gloo Mesh and Gloo Gateway, enabling federated GraphQL queries of your APIs using your service mesh and API gateways. No additional GraphQL servers required!

Combine the developer-friendly GraphQL query language for APIs with Istio’s ability to secure, manage, and observe application traffic across microservices. This eliminates the need for a distinct system of servers and schema libraries of parsers and resolvers for GraphQL; all of your policies and requests can be managed in Envoy Proxy filters. Leveraging the existing capabilities Solo.io provides via Envoy, you can scale from single, monolithic GraphQL APIs to a federated graph spanning multiple clusters. 

Get started with Gloo Gateway with GraphQL today

When should you use GraphQL?

Here are a few common use cases where GraphQL could be a good alternative to traditional REST APIs.

Mobile applications

Mobile apps need to deal with bandwidth limits and slow networks. If you are a mobile developer who needs to optimize an application for speed and bandwidth, GraphQL can help by batching multiple requests into a single network query to reduce the total number of mobile application requests. It also reduces the load on the response returned by the server, because only the data fields actually used by the mobile application are transmitted.

Complex environments

If you are developing an application that interacts with databases, legacy systems, and third-party APIs, GraphQL can help reduce complexity and improve efficiency. It lets you clearly encapsulate how to get data from multiple resources, without specifying where the resources reside. It adds an abstraction layer that hides the complexity of the underlying system.

Microservices applications

Today, a common development pattern is decomposing applications into independent microservices, which communicate via APIs. As the number of microservices in the environment increases, GraphQL offers various benefits, including efficient request routing, graceful error handling, and parallel request execution. 

With GraphQL, it is easier to make requests from multiple microservices. Your application points at one endpoint, and GraphQL routes requests to all the appropriate microservices and returns results. A single GraphQL query can contain multiple requested resources, and those requests can be processed in parallel by many microservices. GraphQL also uses strongly typed application requests that can fail completely or partially, returning useful data and clear, understandable errors.

Rapid application prototyping

When prototyping new applications, speed is of the essence. GraphQL has features to help improve development productivity, allowing front-end teams to work without relying on back-end teams. GraphQL can also be applied in front of existing APIs, adding capabilities like authentication or authorization, without modifying the original API.

GraphQL best practices

1. Ensure naming consistency in the schema

Consistent naming within GraphQL schemas makes identifying data easier and more efficient. If you don’t set up schema naming and adhere to a specific standard, you can find different names or properties in the same schema that refer to the same data. This can cause problems further down the road.

Make sure that naming conventions for fields, data types, pages, and so on, are efficient and always follow the same standards. A good naming convention to use with GraphQL is camelCase for fields and PascalCase for types.

2. Consider future modifications to the schema 

GraphQL schemas will definitely change in the future. This should be taken into account when designing the architecture. What if your web application grows and you need to add more data and fields to your schema? Make sure there is room for modifications and extensions, otherwise you might have to make breaking changes further down the line. You might need to remap your entire schema, wasting resources and time.

3. Eliminate illogical fragments

In GraphQL, fragments are pieces of logic that can be shared simultaneously between queries and mutations. Fragments help ensure that every query is short, readable, and consistent. Unfortunately, some fragments can do more harm than good if not used correctly.

One way to ensure that all fragments are really required is to use them only in schema fields that have logical meaning. Adding fragments incorrectly or illogically can have the opposite effect and make a query hard to read.

4. Avoid hard-coded arguments

If you are a GraphQL beginner, avoid hard-coded parameters that embed data directly into source code. It is better to use variables for all GraphQL parameters. Hard-coded parameters embed everything, including sensitive data, into query strings. This exposes sensitive information and can be easily accessed by malicious individuals.

In addition to the obvious privacy risks of hard-coded parameters, there are also caching issues. When trying to cache API requests, hard-coded parameters can take up space and degrade overall cache performance.

5. Establish an error handling plan

Modern applications should expect failure and be built to handle failure. Error handling is a backup plan for responding to errors and providing recovery solutions.

Build in error handling from the start to ensure that your application always has a valid payload response, even under failure scenarios and as it grows and scales. This can allow developers and operations staff working on the system to pinpoint what went wrong.

See the benefits of Gloo Gateway with GraphQL today!

BACK TO TOP