Crash course GraphQL for iOS - What is GraphQL? (Part 1)

May 06, 20218 min read#iOS, #GraphQL

In my latest project, we are using GraphQL for network communication between clients and servers.

My experience with learning GraphQL in this short period of time is that the learning curve is quite steep since the mechanism of GraphQL is very different to what I am used to, which is REST.

That’s the motivation for this series of blog post to give you a quick overview of GraphQL, how to integrate GraphQL into iOS apps in a testable way, and how to mock a GraphQL server to provide response by using embedded JSON files.

What’s GraphQL?

GraphQL is a query language for your API, and a server-side runtime for executing queries 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

GraphQL is an open-source API design paradigm. Facebook introduced GraphQL in 2012, and it’s been powering Facebook’s mobile apps ever since. In contrast to REST, a GraphQL API exposes only a single endpoint, and the consumers of the API can specify the data they need via a query language.

GraphQL vs Rest

A REST API is an architectural concept for network-based software. GraphQL, on the other hand, is a query language, a specification, and a set of tools that operates over a single endpoint using HTTP. In addition, over the last few years, REST has been used to make new APIs, while the focus of GraphQL has been to optimize for performance and flexibility.

The following parts are summary from the detail explanations available here.

Resources

The core idea of REST is the resource. Each resource is identified by a URL, and you retrieve that resource by sending a GET request to that URL. This is an example of a book endpoint:

// GET /books/1

{
  "title": "Black Hole Blues",
  "author": {
    "firstName": "Janna",
    "lastName": "Levin"
  }
  // ... more fields here
}

GraphQL is quite different in this respect, because in GraphQL these two concepts are completely separate. The data type that the server can handle and the shape of the resources returning to the client are separated.

First we can define some types for the contract between servers and clients.

type Book {
  id: ID
  title: String
  published: Date
  price: String
  author: Author
}

type Author {
  id: ID
  firstName: String
  lastName: String
  books: [Book]
}

To be able to actually access a particular book or author, we need to create a Query type in our schema:

type Query {
  book(id: ID!): Book
  author(id: ID!): Author
}

Now, we can send a request similar to the REST request above, but with GraphQL this time:

// GET /graphql?query={ book(id: "1") { title, author { firstName } } }

{
  "title": "Black Hole Blues",
  "author": {
    "firstName": "Janna",
  }
}

This is the summary of similarities and differences between REST and GraphQL:

  • Similar: Both have the idea of a resource, and can specify IDs for those resources.
  • Similar: Both can be fetched via an HTTP GET request with a URL.
  • Similar: Both can return JSON data in the request.
  • Different: In REST, the endpoint you call is the identity of that object. In GraphQL, the identity is separate from how you fetch it.
  • Different: In REST, the shape and size of the resource is determined by the server. In GraphQL, the server declares what resources are available, and the client asks for what it needs at the time.

URL Routes vs GraphQL Schema

In today’s REST APIs, the API is usually described as a list of endpoints:

GET /books/:id
{
  "title": "Black Hole Blues",
  "author": {
    "firstName": "Janna",
    "lastName": "Levin"
  }
  // ... more fields here
}

GET /authors/:id
GET /books/:id/comments
POST /books/:id/comments

In GraphQL, you don’t use URLs to identify what is available in the API. Instead, you use a GraphQL schema:

type Query {
  book(id: ID!): Book
  author(id: ID!): Author
}

type Mutation {
  addComment(input: AddCommentInput): Comment
}

type Book { ... }
type Author { ... }
type Comment { ... }
input AddCommentInput { ... }
  • Similar: The list of endpoints in a REST API is similar to the list of fields on the Query and Mutation types in a GraphQL API. They are both the entry points into the data.

Similar: Both have a way to differentiate if an API request is meant to read data or write it.

  • Different: In GraphQL, you can traverse from the entry point to related data, following relationships defined in the schema, in a single request. In REST, you have to call multiple endpoints to fetch related resources.
  • Different: In GraphQL, there’s no difference between the fields on the Query type and the fields on any other type, except that only the query type is accessible at the root of a query. For example, you can have arguments in any field in a query. In REST, there’s no first-class concept of a nested URL.
  • Different: In REST, you specify a write by changing the HTTP verb from GET to something else like POST. In GraphQL, you change a keyword in the query.

Route Handlers vs. Resolvers

rest_vs_graphql

  • Similar: Endpoints in REST and fields in GraphQL both end up calling functions on the server.
  • Similar: Both REST and GraphQL usually rely on frameworks and libraries to handle the nitty-gritty networking boilerplate.
  • Different: In REST, each request usually calls exactly one route handler function. In GraphQL, one query can call many resolvers to construct a nested response with multiple resources.
  • Different: In REST, you construct the shape of the response yourself. In GraphQL, the shape of the response is built up by the GraphQL execution library to match the shape of the query.

Pros and Cons

Pros

  • Clients have the ability to dictate exactly what they need from the server, and receive that data in a predictable way.
  • It’s fast since clients can avoid overfetching.
  • Strongly-typed which allows API consumers to know exactly what data is available, and in what form it exists.
  • As you make changes to your API, your documentation will evolve with you, saving you valuable time.
  • With detailed error messages, It’s easier for developers to understand what errors occur so they can resolve issues quicker.

Cons

  • GraphQL has a very high learning curve.
  • GraphQL doesn’t inherently allow for file uploads.
  • Queries always return a HTTP status code of 200, regardless of whether or not that query was successful.
  • Lack of built-in caching support.

Conclusion

In this article, I have given an overview about GraphQL and compare it with REST.

If you have a simple REST API and deal with data that is relatively consistent over time, you would be better off sticking with your REST API. For companies that deal with rapidly-changing data, and have the engineering resources to devote to rearchitecting their API platforms, GraphQL can solve many of the pain points experienced with REST APIs.

One thing I want to emphasize: From front-end perspective, GraphQL is just another standard to transfer data between clients and servers. For frontend developers, this standard should not change much the way you create your applications if you have separated your networking code and UI code in the correct way.


Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024