Ap­plic­a­tions on the web use APIs (ap­plic­a­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­cially has developed into a complete premium solution in the past years due to its sim­pli­city.  

But even though the success of REST ar­chi­tec­ture is quite im­press­ive, there are still in­ter­est­ing al­tern­at­ives such as GraphQL that are just as capable. The query language and runtime en­vir­on­ment from the Facebook company can certainly keep up with SOAP and REST, although its ad­vant­ages 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­ment­a­tion

What is GraphQL?

GraphQL is an SQL-like query language including runtime en­vir­on­ment and type system, developed by Facebook in 2012. Ori­gin­ally, it was intended ex­clus­ively for internal use. The back­ground was the redesign of the native mobile Facebook apps for iOS and Android, which showed in­creas­ingly weaker per­form­ance due to the in­creas­ing com­plex­ity. Es­pe­cially for the delivery of newsfeed data, the large cor­por­a­tion had to find an adequate solution in which the re­la­tion­ship between retrieved in­form­a­tion and necessary server queries was sat­is­fact­ory. 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 ele­ment­ary com­pon­ents that char­ac­ter­ise the open source project:  

  • Query language: First and foremost, the GraphQL concept describes a query language that allows programs un­com­plic­ated 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­ised by a high degree of flex­ib­il­ity. 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 spe­cific­ally 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 spe­cific­a­tions. The in­di­vidu­al system created in this way serves GraphQL as a point of reference for val­id­at­ing queries and rejecting incorrect queries. 
  • Runtime en­vir­on­ment: Lastly, GraphQL also provides various server runtime en­vir­on­ments for executing GraphQL queries. For this purpose, libraries for various pro­gram­ming languages are available – for example Go, Java, JavaS­cript, PHP, Python, and Ruby. So you prac­tic­ally have free choice regarding the language of your personal GraphQL API. However, the runtime en­vir­on­ment is ex­clus­ively re­spons­ible for the con­ver­sion (parsing) and val­id­a­tion of the queries and for the seri­al­isa­tion of the responses (con­ver­sion of the objects into a cor­res­pond­ing byte sequence). Saving and de­term­in­ing the data (e.g. in a database) is part of the task area of your web ap­plic­a­tion. 

The interplay of query language, type system, and runtime en­vir­on­ment ensures a highly con­vert­ible API framework. This is not only ac­cess­ible across platforms and ap­plic­a­tions, but can also be perfectly adapted to the char­ac­ter­ist­ics of your web ap­plic­a­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 JavaS­cript framework Node.js.  

What dis­tin­guishes GraphQL?

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

  • Hier­arch­ic­al structure: Data sets that can be accessed via GraphQL APIs have a hier­arch­ic­al structure. Re­la­tion­ships between the in­di­vidu­al objects can be created auto­mat­ic­ally; even complex queries can be for­mu­lated (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­larly suitable for graph-oriented databases such as Janus­Graph and for user in­ter­faces, which are usually also struc­tured hier­arch­ic­ally.  
  • Strong typi­fic­a­tion: Each level of a GraphQL query cor­res­ponds to a specific type, with each type de­scrib­ing a set of available fields. However, this type system can more than auto­mat­ic­ally determine whether a query is for­mu­lated correctly or not. Like SQL, GraphQL can display de­script­ive error messages during de­vel­op­ment or before the query is sent, thanks to its strict typi­fic­a­tion.  
  • Flex­ib­il­ity: GraphQL allows you to start flexible queries. It also gives you a good amount of freedom and ad­vant­ages 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­pletely in­de­pend­ently of the team re­spons­ible 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­tern­at­ive 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­port­ance and com­plex­ity of mobile web ap­plic­a­tions. Es­pe­cially with these ap­plic­a­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­form­a­tion defined in the query, so that neither more nor less data than required is sent via the interface. With com­par­able REST APIs, you can only query one specific data set each time where it is com­pletely displayed. In a direct com­par­is­on of "GraphQL vs. REST," Face­book's query concept proves to be much more precise and efficient, which benefits your ap­plic­a­tion's per­form­ance. In turn, this pays off es­pe­cially 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­cially if you want to offer open APIs where you cannot control the query behaviour of third-party clients. It is possible that too many queries could crash the server (in­ten­tion­ally or un­in­ten­tion­ally). 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­form­ance.  

In addition, im­ple­ment­ing a caching procedure for non-change­able queries with GraphQL is much more com­plic­ated than for queries via a REST interface. The latter can be cached using the caching methods of the HTTP spe­cific­a­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­vant­ages 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­plic­a­tion is based on the JavaS­cript runtime en­vir­on­ment Node.js, GraphQL.js, it is suitable as a basis for the im­ple­ment­a­tion.  

Note

A list of available GraphQL libraries and client ap­plic­a­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 JavaS­cript ap­plic­a­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 JavaS­cript library GraphQL.js, you should use the JavaS­cript package manager npm (Node Package Manager) and the following command:  

npm install --save graphql

Al­tern­at­ively, you can also get the library from the package and de­pend­ency manager Yarn, developed by Facebook (mostly) and Google:  

yarn add graphql

In both cases, a current version of Node.js must be installed (re­com­men­ded: Node v6.0.0 or higher).  

Step 2: the first query scheme

To enable your ap­plic­a­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­plic­a­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­pon­ents in the various steps of this GraphQL tutorial, created your first query schema, and started your own server, you can then fa­mil­i­ar­ise yourself with all the possible query inputs at your leisure.  

More in­form­a­tion and detailed ex­plan­a­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