GraphQL
Applications on the web use APIs (application programming interfaces) 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 established standards like SOAP or REST, which provide a basic structure for your API. They can easily be controlled with any common programming language – the latter architecture especially has developed into a complete premium solution in the past years due to its simplicity.
But even though the success of REST architecture is quite impressive, there are still interesting alternatives such as GraphQL that are just as capable. The query language and runtime environment from the Facebook company can certainly keep up with SOAP and REST, although its advantages come into play for more complex queries, among other things.
- DNS management
- Easy SSL admin
- API documentation
What is GraphQL?
GraphQL is an SQL-like query language including runtime environment and type system, developed by Facebook in 2012. Originally, it was intended exclusively for internal use. The background was the redesign of the native mobile Facebook apps for iOS and Android, which showed increasingly weaker performance due to the increasing complexity. Especially for the delivery of newsfeed data, the large corporation had to find an adequate solution in which the relationship between retrieved information and necessary server queries was satisfactory. 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 understand how GraphQL works, you have to deal with the three elementary components that characterise the open source project:
- Query language: First and foremost, the GraphQL concept describes a query language that allows programs uncomplicated access to an API. While other interface architectures only allow very strict queries, which often only allow access to a single resource, GraphQL queries are characterised by a high degree of flexibility. 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 specifically 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 structures, 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 specifications. The individual system created in this way serves GraphQL as a point of reference for validating queries and rejecting incorrect queries.
- Runtime environment: Lastly, GraphQL also provides various server runtime environments for executing GraphQL queries. For this purpose, libraries for various programming languages are available – for example Go, Java, JavaScript, PHP, Python, and Ruby. So you practically have free choice regarding the language of your personal GraphQL API. However, the runtime environment is exclusively responsible for the conversion (parsing) and validation of the queries and for the serialisation of the responses (conversion of the objects into a corresponding byte sequence). Saving and determining the data (e.g. in a database) is part of the task area of your web application.
The interplay of query language, type system, and runtime environment ensures a highly convertible API framework. This is not only accessible across platforms and applications, but can also be perfectly adapted to the characteristics of your web application. This means you can easily integrate the GraphQL interface into your project's code – regardless of whether you are using the Python framework Django, the Ruby framework Rails, or the JavaScript framework Node.js.
What distinguishes GraphQL?
One of the main features of GraphQL is the simplicity of the query language, which makes it as easy as possible for developers 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 JavaScript format JSON (JavaScript Object Notation). Consequently, sending an exactly fitting query is not a big challenge if you know the structure of the data that your application needs and formulate it in the query. In addition to the simple creation of queries, GraphQL has the following properties:
- Hierarchical structure: Data sets that can be accessed via GraphQL APIs have a hierarchical structure. Relationships between the individual objects can be created automatically; even complex queries can be formulated (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 particularly suitable for graph-oriented databases such as JanusGraph and for user interfaces, which are usually also structured hierarchically.
- Strong typification: Each level of a GraphQL query corresponds to a specific type, with each type describing a set of available fields. However, this type system can more than automatically determine whether a query is formulated correctly or not. Like SQL, GraphQL can display descriptive error messages during development or before the query is sent, thanks to its strict typification.
- Flexibility: GraphQL allows you to start flexible queries. It also gives you a good amount of freedom and advantages when developing or adapting your interface. As a rule, only a few adjustments have to be made on the server side, whereby the development team can act completely independently of the team responsible for the client component. Furthermore, any changes or extensions to the API can be made without versioning, as additional fields can be added easily and without affecting existing clients.
GraphQL vs. REST – what is the difference 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 alternative to this established HTTP-based and resource-oriented architecture for web services. This was made possible thanks to a development that led Facebook to develop GraphQL in the first place: the increasing importance and complexity of mobile web applications. Especially with these applications 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 information defined in the query, so that neither more nor less data than required is sent via the interface. With comparable REST APIs, you can only query one specific data set each time where it is completely displayed. In a direct comparison of "GraphQL vs. REST," Facebook's query concept proves to be much more precise and efficient, which benefits your application's performance. In turn, this pays off especially for users of mobile devices, who often only have less efficient internet connections.
While the freedom to retrieve data from GraphQL results in many positive features, it can also become a serious security problem, especially 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 (intentionally or unintentionally). 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 performance.
In addition, implementing a caching procedure for non-changeable queries with GraphQL is much more complicated than for queries via a REST interface. The latter can be cached using the caching methods of the HTTP specification (in the browser, for example).
GraphQL tutorial: getting started and GraphQL example
GraphQL gives you the freedom to choose the underlying programming language, thanks to its wide range of ready-to-use libraries. This is also one of the great advantages when implementing 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 application is based on the JavaScript runtime environment Node.js, GraphQL.js, it is suitable as a basis for the implementation.
A list of available GraphQL libraries and client applications for various programming 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 application. In addition to the latter GraphQL.js library, the web framework Express is also used.
Step 1: installing 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
Alternatively, you can also get the library from the package and dependency manager Yarn, developed by Facebook (mostly) and Google:
yarn add graphql
In both cases, a current version of Node.js must be installed (recommended: Node v6.0.0 or higher).
Step 2: the first query scheme
To enable your application 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 appropriate 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 application 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 difference 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 components in the various steps of this GraphQL tutorial, created your first query schema, and started your own server, you can then familiarise yourself with all the possible query inputs at your leisure.
More information and detailed explanations on GraphQL backends and frontends can be found in the tutorial section on the official website of the Facebook API concept.