Ap­pli­ca­tions on the web use APIs (ap­pli­ca­tion pro­gram­ming in­ter­faces) to exchange and process data. If you want other services to access data from your web project, you need to develop and implement an interface like this one. There are some es­tab­lished standards like SOAP or REST, which provide a basic structure for your API. They can easily be con­trolled with any common pro­gram­ming language – the latter ar­chi­tec­ture es­pe­cial­ly has developed into a complete premium solution in the past years due to its sim­plic­i­ty.  

But even though the success of REST ar­chi­tec­ture is quite im­pres­sive, there are still in­ter­est­ing al­ter­na­tives such as GraphQL that are just as capable. The query language and runtime en­vi­ron­ment from the Facebook company can certainly keep up with SOAP and REST, although its ad­van­tages come into play for more complex queries, among other things.  

IONOS Developer API
Manage your hosting products through our powerful API
  • DNS man­age­ment
  • Easy SSL admin
  • API doc­u­men­ta­tion

What is GraphQL?

GraphQL is an SQL-like query language including runtime en­vi­ron­ment and type system, developed by Facebook in 2012. Orig­i­nal­ly, it was intended ex­clu­sive­ly for internal use. The back­ground was the redesign of the native mobile Facebook apps for iOS and Android, which showed in­creas­ing­ly weaker per­for­mance due to the in­creas­ing com­plex­i­ty. Es­pe­cial­ly for the delivery of newsfeed data, the large cor­po­ra­tion had to find an adequate solution in which the re­la­tion­ship between retrieved in­for­ma­tion and necessary server queries was sat­is­fac­to­ry. In 2015, Facebook made the GraphQL source code freely available – by this time it had already regulated almost all data access for the mobile apps. Since 2017, the project has been running under the free OWFa 1.0 license (Open Web Foundation).  

How GraphQL works

To un­der­stand how GraphQL works, you have to deal with the three el­e­men­tary com­po­nents that char­ac­ter­ize the open source project:  

  • Query language: First and foremost, the GraphQL concept describes a query language that allows programs un­com­pli­cat­ed access to an API. While other interface ar­chi­tec­tures only allow very strict queries, which often only allow access to a single resource, GraphQL queries are char­ac­ter­ized by a high degree of flex­i­bil­i­ty. This can be seen in the fact that there is no limit to the number of resources queried and that it is possible to define specif­i­cal­ly which data fields are to be queried. GraphQL allows both reading and writing or changing queries.  
  • Type system: GraphQL also works with its own type system that allows you to describe your API by data types. The data struc­tures, which are defined in this way, then create the actual framework for queries. Each type consists of one or more fields, which in turn contain their own type spec­i­fi­ca­tions. The in­di­vid­ual system created in this way serves GraphQL as a point of reference for val­i­dat­ing queries and rejecting incorrect queries. 
  • Runtime en­vi­ron­ment: Lastly, GraphQL also provides various server runtime en­vi­ron­ments for executing GraphQL queries. For this purpose, libraries for various pro­gram­ming languages are available – for example Go, Java, JavaScript, PHP, Python, and Ruby. So you prac­ti­cal­ly have free choice regarding the language of your personal GraphQL API. However, the runtime en­vi­ron­ment is ex­clu­sive­ly re­spon­si­ble for the con­ver­sion (parsing) and val­i­da­tion of the queries and for the se­ri­al­iza­tion of the responses (con­ver­sion of the objects into a cor­re­spond­ing byte sequence). Saving and de­ter­min­ing the data (e.g. in a database) is part of the task area of your web ap­pli­ca­tion. 

The interplay of query language, type system, and runtime en­vi­ron­ment ensures a highly con­vert­ible API framework. This is not only ac­ces­si­ble across platforms and ap­pli­ca­tions, but can also be perfectly adapted to the char­ac­ter­is­tics of your web ap­pli­ca­tion. This means you can easily integrate the GraphQL interface into your project's code – re­gard­less of whether you are using the Python framework Django, the Ruby framework Rails, or the JavaScript framework Node.js.  

What dis­tin­guish­es GraphQL?

One of the main features of GraphQL is the sim­plic­i­ty of the query language, which makes it as easy as possible for de­vel­op­ers to access the interface. Anyone who is familiar with GraphQL, for example, will quickly realize that the answers received perfectly mirror the questions asked. The output format is the JavaScript format JSON (JavaScript Object Notation). Con­se­quent­ly, sending an exactly fitting query is not a big challenge if you know the structure of the data that your ap­pli­ca­tion needs and formulate it in the query. In addition to the simple creation of queries, GraphQL has the following prop­er­ties:  

  • Hi­er­ar­chi­cal structure: Data sets that can be accessed via GraphQL APIs have a hi­er­ar­chi­cal structure. Re­la­tion­ships between the in­di­vid­ual objects can be created au­to­mat­i­cal­ly; even complex queries can be for­mu­lat­ed (and answered) in a single request based on them. An exchange of several messages between server and client (also called "round trips") is not necessary. This data hierarchy is par­tic­u­lar­ly suitable for graph-oriented databases such as Janus­Graph and for user in­ter­faces, which are usually also struc­tured hi­er­ar­chi­cal­ly.  
  • Strong typ­i­fi­ca­tion: Each level of a GraphQL query cor­re­sponds to a specific type, with each type de­scrib­ing a set of available fields. However, this type system can more than au­to­mat­i­cal­ly determine whether a query is for­mu­lat­ed correctly or not. Like SQL, GraphQL can display de­scrip­tive error messages during de­vel­op­ment or before the query is sent, thanks to its strict typ­i­fi­ca­tion.  
  • Flex­i­bil­i­ty: GraphQL allows you to start flexible queries. It also gives you a good amount of freedom and ad­van­tages when de­vel­op­ing or adapting your interface. As a rule, only a few ad­just­ments have to be made on the server side, whereby the de­vel­op­ment team can act com­plete­ly in­de­pen­dent­ly of the team re­spon­si­ble for the client component. Fur­ther­more, any changes or ex­ten­sions to the API can be made without ver­sion­ing, as ad­di­tion­al fields can be added easily and without affecting existing clients

GraphQL vs. REST – what is the dif­fer­ence between the two API concepts?

The great success of REST in the world wide web has already been mentioned as well as the fact that GraphQL is a serious al­ter­na­tive to this es­tab­lished HTTP-based and resource-oriented ar­chi­tec­ture for web services. This was made possible thanks to a de­vel­op­ment that led Facebook to develop GraphQL in the first place: the in­creas­ing im­por­tance and com­plex­i­ty of mobile web ap­pli­ca­tions. Es­pe­cial­ly with these ap­pli­ca­tions for Android, iOS, etc. the great strength of GraphQL as an API basis becomes apparent: it's possible to get access to all desired data with a single query.  

The GraphQL server instance delivers exactly the in­for­ma­tion defined in the query, so that neither more nor less data than required is sent via the interface. With com­pa­ra­ble REST APIs, you can only query one specific data set each time where it is com­plete­ly displayed. In a direct com­par­i­son of "GraphQL vs. REST," Face­book's query concept proves to be much more precise and efficient, which benefits your ap­pli­ca­tion's per­for­mance. In turn, this pays off es­pe­cial­ly for users of mobile devices, who often only have less efficient internet con­nec­tions.  

While the freedom to retrieve data from GraphQL results in many positive features, it can also become a serious security problem, es­pe­cial­ly if you want to offer open APIs where you cannot control the query behavior of third-party clients. It is possible that too many queries could crash the server (in­ten­tion­al­ly or un­in­ten­tion­al­ly). A scenario like this is less likely to affect you so quickly when using a REST API. It is therefore much more difficult to implement GraphQL in the backend in such a way that it runs reliably and with a high per­for­mance.  

In addition, im­ple­ment­ing a caching procedure for non-change­able queries with GraphQL is much more com­pli­cat­ed than for queries via a REST interface. The latter can be cached using the caching methods of the HTTP spec­i­fi­ca­tion (in the browser, for example).  

GraphQL tutorial: getting started and GraphQL example

GraphQL gives you the freedom to choose the un­der­ly­ing pro­gram­ming language, thanks to its wide range of ready-to-use libraries. This is also one of the great ad­van­tages when im­ple­ment­ing a GraphQL interface in your app. For example, as a Python fan you can access the Graphene library – or work with the graphql-java|github.com: graphql-java library if your project is based on Java. If your web ap­pli­ca­tion is based on the JavaScript runtime en­vi­ron­ment Node.js, GraphQL.js, it is suitable as a basis for the im­ple­men­ta­tion.  

Note

A list of available GraphQL libraries and client ap­pli­ca­tions for various pro­gram­ming languages can be found on the official GraphQL website.

In the following GraphQL tutorial, we explain how to get started and what the first steps are with the API framework for a JavaScript ap­pli­ca­tion. In addition to the latter GraphQL.js library, the web framework Express is also used.  

Step 1: in­stalling the library

To use GraphQL libraries, you must first install them. For the JavaScript library GraphQL.js, you should use the JavaScript package manager npm (Node Package Manager) and the following command:  

npm install --save graphql

Al­ter­na­tive­ly, you can also get the library from the package and de­pen­den­cy manager Yarn, developed by Facebook (mostly) and Google:  

yarn add graphql

In both cases, a current version of Node.js must be installed (rec­om­mend­ed: Node v6.0.0 or higher).  

Step 2: the first query scheme

To enable your ap­pli­ca­tion to process GraphQL queries, you need a scheme that defines the type "query" and the access point to your interface (also called API root) including resolver function. For a simple GraphQL sample interface that only outputs the message "Hello world," the ap­pro­pri­ate code in the server.js file created for this purpose would look like this:  

var { graphql, buildSchema } = require('graphql'); 
// Build schema based on the GraphQL concept 
var schema = buildSchema(` 
type Query { 
hello: String 
} 
`); 
  
// API root provides a resolver function for each accessing endpoint  
var root = { 
hello: () => { 
return 'Hello world!'; 
}, 
}; 
 
// Execute GraphQL query '{ hello }' and display the corresponding answer graphql(schema, '{ hello }', root).then(response => { 
console.log(response); 
});

Now execute this code with Node.js by entering the command in the terminal.

node server.js

You should then receive the following message:  

{ data: { hello: 'Hello world!' } }

Step 3: your own GraphQL server on an express basis

After you have created a simple query in the previous step and executed it from the command line, it is now time to run a GraphQL API server. This allows the interface to be accessed, for example, via a standard web browser. To do this, first install the ap­pli­ca­tion framework Express mentioned above and the library express-graphql with the following command:  

npm install express express-graphql --save

Then modify the "Hello world!" GraphQL example so that it becomes the basis of your GraphQL server instead of a simple script. To do this, implement the Express module and use the express-graphql library to connect the API server to the HTTP endpoint "/graphql":  

var express = require('express'); 
var graphqlHTTP = require('express-graphql'); 
var { buildSchema } = require('graphql'); 
 
 
// Build schema based on the GraphQL concept 
var schema = buildSchema(` 
type Query { 
hello: String 
} 
`); 
 
// API root provides a resolver function for each accessing endpoint  
var root = { 
hello: () => { 
return 'Hello world!'; 
}, 
}; 
 
var app = express(); 
app.use('/graphql', graphqlHTTP({ 
schema: schema, 
rootValue: root, 
graphiql: true 
})); 
app.listen(4000); 
console.log('Ececute GraphQL API server on localhost:4000/graphql');

As in the previous GraphQL example, open the server.js file with Node.js – with the dif­fer­ence that this time you are not executing a simple query but starting your API server:  

node server.js

The code of the GraphQL Express server not only specifies the scheme and root API, but also the HTTP endpoint "/graphql." The "graphiql: true" entry activates the tool of the same name, which allows you to enter queries via a graphical user interface. Simply open your browser and enter the following address:  

http://localhost:4000/graphql

After you have installed the necessary com­po­nents in the various steps of this GraphQL tutorial, created your first query schema, and started your own server, you can then fa­mil­iar­ize yourself with all the possible query inputs at your leisure.  

More in­for­ma­tion and detailed ex­pla­na­tions on GraphQL backends and frontends can be found in the tutorial section  on the official website of the Facebook API concept.  

Go to Main Menu