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.

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.

Core GraphQL concepts with examples

Retrieving data

The query features of GraphQL allow you to retrieve the required data easily, merge several data sets, and request the required data. For example, the following code below is used to retrieve an author’s profile.

{
  authors(id: "2") {
    id
    name
    books {
      id
      title
    }
  }
}

Modifying data with mutations

In addition to query capabilities, GraphQL provides an efficient and elegant method for modifying data, known as mutations. With GraphQL mutations, executing server-side insert, update, and delete operations is simple. For example, the code below demonstrates how to add an author using the GraphQL API.

mutation addAuthor {
  addAuthor(name: "alex andrew", website: "alexandrew.com") {
    id
    name
    website
  }
}

Using aliases

In addition, aliases allow you to change the names of the fields in response to your needs. For example, the following code shows how aliases are used to retrieve the profiles of two distinct authors.

{
  alex: authors(website: "alexandrew.com") {
    id
    name
    website
  }

 

  orwell: authors(website: "orwellorganization.com") {
    id
    name
    website
  }
}

The following is the response to the above request:

{
  "data": {
    "alex": {
      "id": "1",
      "name": "Alex Andrew",
      "website": "alexandrew.com"
    },
    "orwell": {
      "id": "2",
      "name": "Tom Orwell",
      "website": "orwellorganization.com"
    }
  }
}

Using fragments

Fragment is one the core concepts of GraphQL. With fragments, users may reuse a query section that normally needs many iterations. In the preceding example, we duplicated the ID, name, and name again. To resolve this issue, we can use fragments. The output will be the same.

{
  alex: authors(website: "alexandrew.com") {
    ...authorProfile
  }

  orwell: authors(website: "orwellorganization.com") {
    ...authorProfile
  }
}

fragment authorProfile on Author {
  id
  name
  website
}
Dynamic queries with variables

Lastly, GraphQL natively supports variables. To create dynamic queries, users can use variables. Let’s attempt to retrieve an author’s profile as an example employing variables.

query authorProfile($id: ID!) {
  authors(id: $id) {
    id
    name
    email
  }
}

GraphQL vs. GraphiQL

GraphiQL is an open source, browser-based user interface for interactively exploring and querying features of the GraphQL API. It can also be described as an in-browser integrated development environment (IDE) for GraphQL. 

 

The GraphiQL user interface allows you to create and run tasks, define variables, view task results, and explore patterns. Main parts of the user interface include:

  • Query Pane—the left pane in GraphiQL is the query pane. This is where you write your GraphQL queries and transformations.
  • Query Variables Pane—the lower left pane of GraphiQL is the query variables pane. Here you can define variables used for queries or transformations. Variables must be written in JSON format. When you first access GraphiQL, the query variables pane may collapse at the bottom of the page. Click the Query Variables heading to expand it.
  • Results Pane—the right pane in GraphiQL is the results pane. Here, GraphiQL displays the result of the last executed query or transformation in JSON format. If a query or variant is malformed, the error that caused the query or variant to fail is displayed. GraphiQL highlights fields, parameters, and syntax in queries.

Documentation Explorer Pane—the Documents button expands the Document Explorer window on the right side of the page. You can use it to search or browse your GraphQL schema. This allows you to explore all available queries, variants, fields, types, parameters, and other schema elements.

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.

Enabling GraphQL with Solo Gloo GraphQL

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 GraphQL on Gloo GraphQL today

BACK TO TOP