top of page

GraphQL VS REST

GraphQL logo.

In this blog:

➡️ Find my blog on exposing private GraphQL endpoints here.

➡️ Find my blog on exposing private GraphQL fields here.

What is REST API?


An API is a contract between a client and server, allowing them to exchange information.


REST (Representational State Transfer) created by Dr Roy Fielding, uses HTTP protocol (not surprising, considering Dr Roy Fielding was also involved in the genesis of HTTP itself).


REST API logo.

Based on 6 constraints:


  • Client-server architecture ➡️ Makes it easier to implement and scale clients independently.

  • Stateless ➡️ each query must contain all the necessary information required, to process it. The server also does not store any session data. It is therefore reliable and easier to scale. We will get to drawbacks of this later.

  • Cacheable ➡️ Server must flag responses that are cacheable to improve network efficiency by reducing communication between client and server. Also removes latency between client and server.

  • Uniform Interface ➡️ API in the middle uses a known uniform interface to exchange information. Identifying resources are done using HTTP URLs. When the client requests a certain URL, the server responds with a representation of the product, usually in JSON. However, each message needs to be complete and contain all information necessary for it to be processed. This is done using HTTP methods such as OPTIONS, GET, POST, DELETE, Response codes, and Headers. Finally, a REST API needs to have Hypermedia as the engine of application state, (HATEOAS). This means our messages should include links that allow the client to browse the API – the client should be able to discover all the URLS present in the API.

  • Layered System ➡️ Each layer cannot see beyond surrounding layers. This can be done using CDNs, Firewalls, Load balancers, and API gateways – all of which should be made transparent to the client.

  • Final requirement is code on demand (optional) ➡️ For scenarios where code is downloaded and executed on the server side. An example is the JavaScript that is downloaded on our browsers that make webpages dynamic.


Traditionally web devs consumed APIs using REST, where data entities lived on URLS on a server. When a request was received, the API responds with the full data payload of that entity.

Drawbacks of REST:


  • May need multiple entities at one time ➡️ the request is under fetching the actual data we want.


  • May only want a small subset of a data entity ➡️ so we would over fetch from the API -- bad for the environment.

What is GraphQL?


  • GraphQL is a query language used for APIs, developed by Meta and facilitates efficient communication between client and server ➡️ reads and mutates data in APIs.

  • Usually divided into its schema and its resolvers (not the same as a database schema) ➡️ GraphQL is completely independent from your database.

  • We can define a scheme with our custom objects using the TYPE keyword. A type can have multiple fields like a unique ID, and we make that required with a '!'.

  • user can specify exactly what data they want in the response ➡️ stops the large response objects and multiple calls that can be seen with REST APIs.

  • Provides a type system where you can describe a schema for your data ➡️ gives front-end consumers of the API, the power to explore and request the data they need.

  • It can aggregate multiple resource requests into a single query.

  • Instead of multiple URLS, GraphQL has a single-entry point ➡️ data is fetched by describing it with a syntax that mirrors its return shape in JSON - Client doesn’t need to know where the data sits.

  • Front end describes the data they want, while back end writes code to resolve the request.

  • It is platform-agnostic ➡️ can be implemented with a wide range of programming languages and can be used to communicate with virtually any data store.

  • Every GraphQL API has a query type ➡️ main entry point for a consumer of the API. We can query a list of videos or individual users based on ID. This is how data is read.

  • Once deployed, any developer consuming this API can explore it with a complete understanding of all possible queries and data entities ➡️ so the tool can autocomplete your queries as you type it out in your editor.

Subscriptions and Mutations:


The GraphQL interface sits inbetween the client and Authentication APIs, Core APIs and others.

GraphQL in relation to client and backend.

GraphQL also supports subscriptions and mutations:


GraphQL subscription and mutation.

Example:


Query to fetch all vehicles from a manufacturer:

query GetAllVehicles {
    vehicles {
        name
        vehicleType
	}
}

Add a new vehicle (Mutation):

mutation AddNewVehicle ($name: String!, $petType; vehicleType) {
    addVehicle(name: $name, vehicleType: $vehicleType) {
        id
        name
        vehicleType
    }   
}

Subscriptions:


Subscriptions are GraphQL’s way for clients to receive notifications on data modifications.


Subscription method in GraphQL.

GraphQL VS REST:

Some comparisons:

REST API.

REST centres around resources, which are identified by a URL, like the ones above.


Both GraphQL and REST use HTTP, make requests using a URL, and both can return a JSON response in the same shape.


However, with GraphQL, we specify the exact resource and fields that we want.

In the REST API, the API implementer would decide what fields are related to the resource we specified and will add them to the query, even though we did not need it. This is overfetching.


GraphQL advantage ➡️


  • Uses schema instead of a URL.

  • You could form a complex query in GraphQL that fetches additional data based on the relationships defined in the schema. Doing the same in REST is more complicated and requires queries, client side, with multiple requests.


GraphQL disadvantage ➡️


  • Requires libraries to consume someone else’s API. REST allows you to use simple tools like curl or the web browser to send requests.

  • GraphQL requires heavier tools such as schema, GraphQL, Apollo, and codegen.yml, both on client and server side. This may increase upfront costs when implementing GraphQL ➡️ may not be feasible, especially for simple CRUD APIs (Create, Read, Update, Delete).

  • GraphQL is difficult to cache ➡️ REST uses HTTP GET for fetching resources, which has well defined caching behaviours, using content delivery networks, web servers and proxies in multiple web browsers.

  • GraphQL has a single point of entry and uses HTTP POST by default ➡️ this prevents the full use of HTTP caching. It can be done, however is known to be quite difficult to implement correctly.

  • Although it allows clients to query just the data required, this poses a great security risk ➡️ More on GraphQL vulnerabilities in this blog.


Steps can be taken to mitigate certain risks, however, the costs involved should also be factored in and simply increases the complexity of GraphQL. The feasibility must be weighed based on business infrastructure and requirements.

コメント

5つ星のうち0と評価されています。
まだ評価がありません

評価を追加
  • GitHub
  • Twitter
  • LinkedIn
bottom of page