Luna Tech

Tutorials For Dummies.

GraphQL Intro

2021-09-12


Q & A

Reference

Try it out

Basics

Q: What is GraphQL

A:

Q: What are the use cases of GraphQL?

A: A modern way to build in-query APIs.

Q: What problems does GraphQL solve?

A: Under-fetching and over-fetching in consuming REST APIs, especially in an SPA app. The biggest advantage is to make sure you get only the data you asked for.

Q: Why under-fetching and over-fetching is an issue?

A: under-fetching means you need to make multiple requests to do your job, while over-fetching means you are getting too much information than you actually need. Both can affect application performance and waste bandwidth.

Objective: use a single request to fetch the exact amount of data we need in our application.

Q: Advantages of adopting GraphQL

A: By using a flexible contract, frontend team collaborate with backend team easily, both teams can work independently and then use GraphQL client and server to hook up the data.

Keypoint: GraphQL acts as a middle man between client and server, it serves the data per client request.

Since the client can control the shape of the data through the request, there’s no longer a need to bother the backend team for shaping a JSON response in a certain way.

Q: What are the differences between GraphQL API and REST API?

A: How the shape of the API response is defined. REST defines the shape on the API Server, for GraphQL, it is done on the client side.

Q: Is GraphQL strongly typed?

A: Yes! And the benefits of strong type are:

GraphQL Frameworks

Q: What is Apollo?

A: GraphQL is an open specification, anyone can create their own implementation of a GraphQL framework based on the specification. Apollo is one of the most popular ones.

Q: Are there any other frameworks?

A: Yes! GraphQL Yoga, Hasura are also implementations of GraphQL specification. Also, GraphQL is not tied to JS language at all.

Q: Which one to use?

A:

Vue and GraphQL

Q: How do these 2 things come together?

A: When client side needs to fetch data from backend, it can either use RESTful API or use GraphQL query language and request from the GraphQL backend server.

Q: How do I use it with the HTTP method way?

A: The simplest way is just use the built-in fetch function and create a POST request with a query.

fetch("/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: "query { currentUser { id } }" }),
});

Q: How about using a GraphQL client library?

A: It can encapsulate the lower-level details that we’ve put in the fetch function to a nicer API, so it’s easier to work with.

Just like there’s a GraphQL server library for each backend language, there’s at least one GraphQL client library for each frontend framework.

If you want to use Apollo client to integrate with Vue, then you can check Vue Apollo library.