GraphQL is one of the options for transmitting information in a client-server model, called the Application Programming Interface. In the history of the development of computer technology, there have already been very useful examples of building an API, and some of them still work today. The relationship between the components of the system is a key factor for building information systems, and today GraphQL is one of the most advanced options.
Even much simpler applications that may run into the limitations of traditional REST APIs, can easily use GraphQL, even though it was developed for Facebook needs first.
What is API?
Let’s look at what API is (application programming interface). This is a description of the ways (a set of classes, procedures, functions, structures or constants) that one computer program can interact with another program. It is usually included in the description of an Internet protocol (for example, RFC), a software framework (framework), or a standard for naming operating system functions. It is often implemented by a separate software library or operating system service and is used by programmers to write all kinds of applications.
The API defines the functionality that the program (module, library) provides, and allows you to abstract how exactly this functionality is implemented. If the program (module, library) is considered as a black box, then the API is a lot of “handles” that are available to the user of this box. Software components communicate with each other through the API. In this case, usually, the components form a hierarchy - high-level components use the API of low-level components, and those, in turn, use the API of even lower-level components.
Protocols for transmitting data over the Internet are built according to this principle. The standard protocol stack (OSI network model) contains 7 layers, from the physical layer of bit transfer to the level of application protocols like HTTP and IMAP. Each level uses the functionality of the previous “underlying” level of data transfer and, in turn, provides the necessary functionality to the next “overlying” level.
It is important to note that the concept of a protocol is close in meaning to the concept of API; in the first case we are talking about data transfer, and in the second - the interaction of applications.
The main policies for releasing an API are:
- Private: The API is for internal company use only.
- Partner: Only specific business partners can use the API. For example, transportation network companies such as Uber and Lyft allow approved third-party developers to directly order rides from within their apps. This allows the companies to exercise quality control by curating which apps have access to the API and provides them with an additional revenue stream.
- Public: The API is available for use by the public. For example, Microsoft makes the Microsoft Windows API public, and Apple releases its APIs Carbon and Cocoa so that software can be written for their platforms.
The library API of functions and classes includes a description of signatures and semantics of functions. The main challenges of existing multi-level API systems are:
- The difficulty of porting program code from one API system to another (for example, when replacing the operating systems);
- Loss of functionality when moving from a lower level to a higher one. Roughly speaking, each “layer” of the API is created to facilitate the execution of some standard set of operations. But at the same time, it is really difficult or it becomes fundamentally impossible to perform some other operations that provide a lower level of API.
REST
REST (Representational State Transfer) - an architectural style of interaction between components of a distributed application on the network. REST is a consistent set of constraints that are considered when designing a distributed hypermedia system. In certain cases (online stores, search engines, other data-based systems), this leads to increased productivity and simplified architecture. Broadly speaking, components in REST interact like client-server interactions on the World Wide Web. REST is an alternative to RPC.
On the Internet, a remote procedure call can be a regular HTTP request (usually “GET” or “POST”; such a request is called a “REST request”), and the necessary data is transmitted as request parameters. For web services built with REST in mind (that is, not violating their restrictions), the term “RESTful” is used.
Unlike SOAP-based web services (web services), there is no “official” standard for a RESTful web API. The fact is that REST is an architectural style, while SOAP is a protocol. Although REST is not a standard in itself, most RESTful implementations use standards such as HTTP, URL, JSON, and XML. The key to REST is the resource. Each resource is identified by its URL, and to get the resource, you need to send a GET request to this URL. Most likely, the answer will come in JSON format, since it is this format that is used now in most APIs.
One of the notable features of REST is that the type, or form, of the resource, and the method of obtaining the resource are linked together. GraphQL is quite different in this aspect because in GraphQL these two concepts are completely separate from each other.
Here are some similarities and differences between REST and GraphQL:
Similarity | Difference |
---|---|
There is a concept of a resource; it is possible to assign identifiers for resources | In REST, the endpoint you call is the essence of the object. In GraphQL, the entity of an object is separated from exactly how you get it |
Resources can be retrieved using a GET request for an HTTP URL | In REST, the structure and volume of a resource are determined by the server. In GraphQL, the server determines the set of available resources, and the client indicates the data it needs directly in the request |
The response to the request may return data in JSON format | In GraphQL, you can move from the entry point to related data within a single query, following the relationships defined in the schema. In REST, in order to get related resources, you will have to execute requests to several endpoints |
The list of endpoints in the REST API is similar to the list of fields in the Query and Mutation types used in the GraphQL API. Both are entry points for data access | In GraphQL there is no difference between fields of the Query type and fields of any other type, except that only the query type is available at the root of the query. For example, in your request, any field may have arguments. In REST, there is no concept of a first-class in the case of a nested URL |
It is possible to distinguish between requests to the API for reading and writing data | In REST, you define a data record by changing the HTTP request method from GET to something like POST. In GraphQL, you change the keyword in the query |
Endpoints in REST and fields in GraphQL end up calling functions on the server | In REST, each request usually calls exactly one route handler function. In GraphQL, a single query can call many recognizer functions to build a complex answer with many embedded resources |
Both REST and GraphQL usually rely on frameworks and libraries for routine networking | In REST, you build the response form yourself. In GraphQL, the response form is defined by the library that runs GraphQL to match the query form |
Why GraphQL?
GraphQL does not use URLs to identify what is available to you in the API. Instead, a GraphQL schema is used. On the other hand, GraphQL does not yet have as many integration tools and solutions as REST. For example, using HTTP caching, you cannot cache the results of the GraphQL API as easily for the results of the REST API. However, the community is working hard to improve tools and infrastructure, and you can use tools like Apollo Client and Relay to cache GraphQL.
Facebook has opened its groundwork related to the GraphQL query language, which defines a protocol for efficient data retrieval. GraphQL combines high flexibility, sufficient to describe all the data streams on Facebook, with simplicity for learning, which contributes to the rapid introduction of the language in new products.
A draft GraphQL specification, a reference implementation in JavaScript, a library with a parser for C / C ++, server bindings for various programming languages (Go, Ruby, Scala, Java, .Net, Python) and a set of related tools, including one working, are available for download. in the browser, an integrated environment for generating GraphQL queries and server components for swapi and express. The code is open under the BSD license.
In general, GraphQL is a syntax that describes how to request data and is mainly used by the client to download data from the server. GraphQL has three main characteristics:
- It allows the client to specify exactly what data they need
- Facilitates aggregation of data from multiple sources
- Uses a type system to describe data
Over the past few years, GraphQL has been actively used on Facebook and serves as the basis for abstracting data streams in mobile applications for Android and iOS. GraphQL allowed avoiding the practice of developing mobile applications in the form of an add-on over a variant of the Facebook site for mobile devices towards self-sufficient programs with execution logic on the client-side.
When implementing the Model-View paradigm, the JSON format is perfect for receiving data, but existing methods for sending requests, such as REST and ad hoc, did not meet the requirements of Facebook and required the removal of part of the logic to the server-side, without proper universality. Facebook tried to solve this problem in GraphQL and over the past three years has transferred all its mobile applications to this technology.
In GraphQL, the composition of the query result is dictated by the client and contains only the necessary data set - only what the client requested and nothing more. The request is made out in the form of a hierarchical set of fields, and the answer comes in the mirrored JSON format with the necessary data filled in. The correctness of the request is provided through the built-in type checking system.
GraphQL features that distinguish it from other means of building interaction:
- Explicit specification of the data form - the response mirrors the fields specified in the request, which allows you to know exactly what data will be received and what type it will be
- A hierarchical organization that allows you to track the relationship between objects without the need to send repeated queries and the formation of complex conditions for merging (unlike RESTful-systems and SQL). The data hierarchy is set using the structure in the form of a graph and perfectly combines with the needs that arise when building user interfaces
- Hard typing - each level of the GraphQL query is associated with a specific type and a type is declared for each field (similar to SQL) This approach allows you to identify errors at the stage before the query is executed and makes it possible to improve the quality of client programs
- GraphQL is just a protocol that does not impose any requirements on the nature of the repository. On the server, a specific function is responsible for each GraphQL field, which makes it easy to adapt interaction with GraphQL clients with existing codebases without changing existing storage schemes and business logic
- The ability to obtain information about the data supported by the server. You can request a list of supported types from the GraphQL server and get more complete information about the capabilities of the API provided by the server, without the need to study the code and specifications
- Independence of the server API version - since the form of the returned data is set by the client, the server API can be expanded without the risk of breaking compatibility with client software. For example, new field handlers may be implemented on the server, and will be applied only to versions of clients that support these fields, and will be ignored for old clients
And the list of companies that already support GraphQL is already interesting enough to consider:
- Airbnb
- AWS
- Extreme Networks
- GitHub
- Hasura
- HomeAway
- IBM
- Intuit
- Neo4j
- PayPal
- Shopify
GraphQL Examples
GraphQL is often presented as a revolutionary new way of understanding the API. Instead of working with endpoints that are hard-defined on the server, you can get exactly the data you need with a single request. GraphQL is flexible when implemented in an organization; it makes the collaboration of front-end and back-end development teams smoother than ever before.
However, in practice, both of these technologies involve sending an HTTP request and receiving some kind of result, and many elements from the REST model are built into GraphQL.
As described in GraphQL documentation “GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.
A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type. The following example shows how to work with the information of the user:
type Query {
me: User
}
type User {
id: ID
name: String
}
And each field will have some information to return:
function Query_me(request) {
return request.auth.user;
}
function User_name(user) {
return user.getName();
}
And simple request will looks like:
{
me {
name
}
}
And it will generate the following JSON on the request:
{
"me": {
"name": "Luke Skywalker"
}
}
Code language: JavaScript (javascript)
This simple example shows how to work with GraphQL. Please visit https://graphql.org/ to get more information about GraphQL functionality and usage.
Conclusion
In conclusion, we want to say that GraphQL is really a step forward compared to REST and cannot be compared directly. GraphQL is a query language and it will be indispensable when customers need to receive a variety of information from servers. In this case, you would have to rewrite your API every time there was a need for a new server request form. GraphQL makes your server versatile in terms of requested and received information.
Svitla Systems developers and architects will always help you understand the need to use modern technologies in your project, including GraphQL. We wish you the successful use of the latest methodologies and development tools in your future projects.