Reader small image

You're reading from  Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

Product typeBook
Published inSep 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804613276
Edition2nd Edition
Languages
Concepts
Right arrow
Author (1)
Sourabh Sharma
Sourabh Sharma
author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma

Right arrow

Getting Started with GraphQL

In this chapter, you will learn about the fundamentals of GraphQL, including its schema definition language (SDL), queries, mutations, and subscriptions. The GraphQL API is popular in hand-held device-based apps such as mobile apps because it is fast and efficient in fetching the data and better than REST in certain cases. Therefore, it is important to learn about GraphQL. You will learn more about its comparison with REST in the Comparing GraphQL with REST section in this chapter. After completing this chapter, you will know the basics of GraphQL, including its semantics, schema design, and everything you need to develop a GraphQL-based API using Spring and Spring Boot.

We will cover the following topics in this chapter:

  • Getting to know GraphQL
  • Learning the fundamentals of GraphQL
  • Designing a GraphQL schema
  • Testing GraphQL queries and mutations
  • Solving the N+1 problem

Technical requirements

This chapter covers the theory behind GraphQL and related concepts. It is advised to go through this chapter first to develop and test the GraphQL-based service code presented in the next chapter.

Getting to know GraphQL

You might have heard of or be aware of GraphQL, which has become more popular in the API space in past few years and is becoming the preferred way of implementing APIs for handheld devices and the web.

GraphQL is a declarative query and manipulation language and server-side runtime for APIs. GraphQL empowers the client to query exactly the data they want – no more, no less.

We’ll discuss its brief history in the next subsection.

A brief history of GraphQL

In 2011, Facebook was facing challenges in terms of improving the performance of its website on mobile browsers. They started building their own mobile app with mobile-native technologies. However, APIs were not up to the mark because of hierarchical and recursive data. They wanted to optimize their network calls. Note that in those days, mobile network speed was in Kb/s in some parts of the world. Having a fast, high-quality mobile app was going to be the key to their success, since...

Learning the fundamentals of GraphQL

GraphQL APIs contain three important root typesquery, mutation, and subscription. These are all defined in the GraphQL schema using special SDL syntax.

GraphQL provides a single endpoint that returns the JSON response based on the request, which can be a query, a mutation, or a subscription.

First, let’s understand queries.

Exploring the Query type

The Query type is used for reading operations that fetch information from the server. A single Query type can contain many queries. Let’s write a query using SDL to retrieve the logged-in user, as shown in the following GraphQL schema:

type Query {  me: LogginInUser
  # You can add other queries here
}
type LoggedInUser {
  id: ID
  accessToken: String
  refreshToken: String
  username: String
}

Here, you have done two things:

  • You have defined the query root of the GraphQL interface, which contains...

Designing a GraphQL schema

A schema is a GraphQL file that is written using DSL syntax. Primarily, it contains root types (query, mutation, and subscription), and the respective types that are used in root types, such as object types, scalar types, interfaces, union types, input types, and fragments.

First, let’s discuss these types. You learned about root types (query, mutation, and subscription) and object types in the previous section. Let’s now learn more about scalar types.

Understanding scalar types

Scalar types resolve concrete data. There are three kinds of scalar types – built-in scalar types, custom scalar types, and enumeration types. Let’s discuss built-in scalar types first. GraphQL provides the following five kinds of built-in scalar types:

  • Int: This stores integers, and is represented by a signed 32-bit integer.
  • Float: This stores a signed, double-precision, floating-point value.
  • String: This stores a sequence of UTF...

Testing GraphQL queries and mutations

Let’s write queries and mutations in a real GraphQL schema to test the skills you have learned up to this point using GitHub’s GraphQL API explorer. Let’s perform the following steps:

  1. First, go to https://docs.github.com/en/graphql/overview/explorer.
  2. You might have to authorize it using your GitHub account, so that you can execute GraphQL queries.
  3. GitHub Explorer is based on GraphiQL. It is divided into three vertical sections (from left to right in the gray area in Figure 13.1):
    • The left-hand section is divided into two subsections – an upper section for writing queries and a bottom section for defining variables.
    • The middle vertical section shows the response.
    • Normally, the rightmost section is hidden. Click on the Docs link to display it. It shows the respective documentation and schema, along with the root types that you can explore.
Figure 13.1 – GraphQL API Explorer

Figure 13.1 – GraphQL API Explorer...

Solving the N+1 problem

The N+1 problem is not new to Java developers. You might have encountered this problem while using Hibernate, which occurs if you don’t optimize your queries or write entities properly.

Let’s look at what the N+1 problem is.

What is the N+1 problem?

The N+1 problem normally occurs when associations are involved. There are one-to-many relationships between the customer and the order. One customer can have many orders. If you need to find all the customers and their orders, you can do the following:

  1. First, find all the users. This find operation returns the list of user objects.
  2. Then, find all the orders belonging to each user found in step 1. The userId field acts as the relation between the Order and User objects.

So, here, you fire two queries. If you further optimize the implementation, you can place a join between these two entities (Order and User) and receive all the records in a single query.

If this is so simple...

Summary

In this chapter, you learned about GraphQL, its advantages, and how it compares to REST. You learned how GraphQL solves over-fetching and under-fetching problems. You then learned about GraphQL’s root types – queries, mutations, and subscriptions – and how different blocks can help you design the GraphQL schema. Finally, you understood how resolvers work, how they can lead to the N+1 problem, and the solution to this problem.

Now that you know about the fundamentals of GraphQL, you can start designing GraphQL schemas. You also learned about GraphQL’s client-side queries and how to make use of aliases, fragments, and variables to resolve common problems.

In the next chapter, you will make use of the GraphQL skills you acquired in this chapter to implement GraphQL APIs.

Questions

  1. Is GraphQL better than REST? If yes, then in what way?
  2. When should you use fragments?
  3. How can you use variables in a GraphQL query?

Answers

  1. It depends on the use cases. However, GraphQL performs much better for mobile apps and web-based UI applications and is best suited for service-to-service (s2s) communications.
  2. Fragments should be used while sending a request from the GraphQL client when the response contains an interface or union.
  3. You can use a variable in a GraphQL query/mutation, as shown in the following code. This code used to modify the GraphQL request sent in step 6 of the Testing GraphQL queries and mutations section:
    mutation {  addStar(input: {starrableId: $repoId }) {    clientMutationId  }}

Here, you can see that the $repoId variable is used. You must declare that variable in the named mutation and it can then be used in the mutation’s argument, as shown in the following code snippet:

{  "repoId": "R_kgDOHzYNwg"
}

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern API Development with Spring 6 and Spring Boot 3 - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781804613276
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma