Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
GraphQL Best Practices
GraphQL Best Practices

GraphQL Best Practices: Gain hands-on experience with schema design, security, and error handling

Arrow left icon
Profile Icon Artur Czemiel
Arrow right icon
$39.99
Paperback Oct 2024 422 pages 1st Edition
eBook
$31.99
Paperback
$39.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Artur Czemiel
Arrow right icon
$39.99
Paperback Oct 2024 422 pages 1st Edition
eBook
$31.99
Paperback
$39.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$31.99
Paperback
$39.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

GraphQL Best Practices

Unveiling the Holy Grail of Communication – GraphQL

GraphQL seemed to appear both recently and also a long time ago. We live in such times that it’s hard to define. We can definitely consider the year 2015 as the beginning of GraphQL, as that was when Facebook decided it was the right time to make GraphQL open source and available to everyone. Although GraphQL was primarily created to limit data transfer, as a side effect, it also reduced the need for extensive communication within the development team.

I became deeply interested in GraphQL technology around 2018. Since 2016, I had been trying to solve the communication problem between frontend and backend teams by building a TypeScript-based system that generated a REST application skeleton for backend developers and “enforced” them to implement a system with the appropriate types for each endpoint and return exactly what was specified by the system designer (who worked in a visual graph editor). In...

Technical requirements

To follow this chapter and run the mock backend example, you will need the following:

A GitHub repository has been created for this book, and you can find the code for this chapter here: https://github.com/PacktPublishing/GraphQL-Best-Practices/tree/main/chapter-01.

Understanding the advantage of built-in introspection

Why does GraphQL bring about such significant changes? This is primarily because of introspection. In practice, this means that frontend developers, mobile developers, or any API consumers can send a query to the backend asking about the available resolvers, their parameters, and what will be returned from the backend. Thanks to this mechanism, developers can efficiently communicate with the API without diving into the system documentation.

Introspection is a mechanism that allows developers to see the entire structure of a system. Through introspection, we can not only discover what queries we can execute against the backend but also distinguish between queries for data retrieval and mutations for making changes to the system. Additionally, we receive detailed information about the returned types.

Why wasn’t this concept invented earlier, considering it is so simple and obvious? Well, it has been invented before, for...

Working with GraphQL as a source of truth

I often reminisce about the days without GraphQL with an ironic smile on my face. I remember how, as a frontend developer, I had to call backend developers and ask why a certain field suddenly disappeared or what the name of an endpoint was because I couldn’t remember it anymore. Of course, even in REST, there are specification systems that allow for a detailed description of our backend; however, they don’t enforce it on the backend developer – they only enable it.

I was already interested in the concept of a single source of truth even before GraphQL, but as soon as I understood the power of GraphQL, I immediately decided to teach it to everyone in our company and turn it into a competitive advantage.

Understanding the source of truth

Let’s imagine a scenario where we’re starting a project from scratch without any existing systems in place. Typically, the process involves creating wireframes and...

Creating self-documenting schemas

As you can see from our library schema, even though it doesn’t have documentation, just by looking at it, we know exactly what the system based on this schema is used for. This is clear to every member of the team.

Now, let’s go further, looking at self-documenting schemas – these are GraphQL schemas that contain comprehensive and descriptive naming and connections between nodes, allowing developers to easily understand and interact with the available data and operations. Here, we will look at the different elements that make up these schemas.

Custom scalars

Scalars represent simple primitives in GraphQL. There are five built-in scalars in GraphQL: String, Int, Float, ID, and Boolean. Out of these five scalars, only ID needs to be translated, as it is used to indicate a unique key and can be either a string, a number, or a custom object.

With custom scalars, the situation is different as they behave according to how...

Understanding the GraphQL query language

As I mentioned earlier, introspection is vital, and now I present to you the most important part that benefits from introspection: the GraphQL query language. While REST APIs allow for exposing the JSON schema, which provides information about the API structure, I have rarely encountered good use cases for it throughout my professional career. On the other hand, the GraphQL query language is widely used in a proper manner because the language makes it hard to make mistakes.

When I first started using GraphQL, I had this feeling of “Why didn’t people agree on such a standard earlier?” We didn’t need artificial intelligence or quantum computers for it – all we needed was to communicate and reach a consensus – but now GraphQL is commonly used and it is a standard we needed. While it may not be visibly apparent at this moment, I can confidently say that GraphQL is pushing programming technologies forward...

Mocking GraphQL responses

Mocks refers to data that is used when we don’t have the system implementation yet. Their purpose is to closely resemble the data that will be returned from a functioning backend.

But how do mocks work? It’s quite simple. Each type, except for custom scalars, ultimately resolves to basic scalars such as String, ID, Float, Int, and Boolean. By knowing the final type and the resolver path, sometimes, even with detailed documentation, we can return very accurate mock values.

Let’s take a look at our simplified Book type:

type Book {
  id: ID!
  title: String!
  author: String!
}
type Query{
  books: [Book!]!
}

If the fields are built-in scalars, we are able to provide mocks just after looking at the type. In the following JSON code, we provide a response for Query.books:

[
  {
    "id": "123abc",
    "title&quot...

Summary

In this chapter, we have reviewed the basics of GraphQL and highlighted its greatest strengths. We have learned how to query the GraphQL backend for its structure and how it is defined in the SDL. These are all solid foundations of GraphQL that will allow us to smoothly progress through this book. If you don’t understand something in the upcoming chapters, you can always come back here.

Before we dive into the heavyweight schema definition in GraphQL, I’d like us to take a look at how GraphQL relates to large language models and how these two technologies can work together seamlessly. In the next chapter, you will learn how to make GraphQL schemas AI-friendly.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Gain detailed guidance for crafting effective GraphQL schemas
  • Explore insights into securing and optimizing GraphQL applications
  • Learn through step-by-step examples, using TypeScript for practical learning
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

In the ever-evolving landscape of web development, GraphQL has emerged as a powerful query language that addresses the limitations of traditional REST APIs. This guide delves deep into GraphQL, starting with its foundational principles and swiftly advancing to complex topics that will equip you with the skills you need to understand this technology. As you progress, you’ll cover advanced concepts such as schema design, security enhancements, and error handling. You'll also explore essential topics such as federation and the transition from REST to GraphQL, gaining a comprehensive understanding of these critical areas. The book helps you learn through practical examples in TypeScript, guiding you through building scalable and secure GraphQL backends. Additionally, you’ll get up to speed with the intricacies of frontend integration. By the end of this book, you’ll have the skills you need to implement real-world GraphQL solutions, creating efficient and robust applications that meet modern web development demands.

Who is this book for?

This book is for developers interested in advancing their knowledge of GraphQL, from beginners curious about the basics to experienced developers looking to refine their schema design and security strategies. It's particularly ideal for backend developers, full-stack professionals, and frontend developers who wish to understand GraphQL from the ground up and apply advanced techniques in real-world scenarios. Additionally, this book is a must-read for anyone looking to make their applications more efficient and robust using GraphQL.

What you will learn

  • Understand the core principles of GraphQL
  • Integrate GraphQL with frontend technologies such as Node.js and Next.js
  • Optimize GraphQL queries for better performance
  • Deploy and maintain GraphQL applications with confidence
  • Explore schema design, security, and error handling
  • Scale GraphQL with modular schemas
Estimated delivery fee Deliver to Russia

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 11, 2024
Length: 422 pages
Edition : 1st
Language : English
ISBN-13 : 9781835467145
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Estimated delivery fee Deliver to Russia

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Oct 11, 2024
Length: 422 pages
Edition : 1st
Language : English
ISBN-13 : 9781835467145
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 89.98
Resilient Cybersecurity
$49.99
GraphQL Best Practices
$39.99
Total $ 89.98 Stars icon

Table of Contents

22 Chapters
Part 1 - Why GraphQL? Chevron down icon Chevron up icon
Chapter 1: Unveiling the Holy Grail of Communication – GraphQL Chevron down icon Chevron up icon
Chapter 2: Applying an AI-Friendly Approach to GraphQL Chevron down icon Chevron up icon
Part 2 - Schema-First Design Patterns Chevron down icon Chevron up icon
Chapter 3: Crafting Effective GraphQL Schemas Chevron down icon Chevron up icon
Chapter 4: Building Pipes Chevron down icon Chevron up icon
Part 3 - Exploring Possible Ways to Use GraphQL Chevron down icon Chevron up icon
Chapter 5: Transitioning from REST to GraphQL Chevron down icon Chevron up icon
Chapter 6: Defining GraphQL Transformers Chevron down icon Chevron up icon
Chapter 7: Understanding GraphQL Federation Chevron down icon Chevron up icon
Part 4 - Advanced GraphQL Chevron down icon Chevron up icon
Chapter 8: Executing Schema-First Systems Chevron down icon Chevron up icon
Chapter 9: Working on the Frontend with GraphQL Chevron down icon Chevron up icon
Chapter 10: Keeping Data Secure Chevron down icon Chevron up icon
Chapter 11: Describing Errors in GraphQL Chevron down icon Chevron up icon
Chapter 12: Documenting your Schema Chevron down icon Chevron up icon
Chapter 13: Tackling Schemas with Visualization Chevron down icon Chevron up icon
Part 5 - From an Idea to a Working Project Chevron down icon Chevron up icon
Chapter 14: From an Idea to a Working Project – Backend Development with GraphQL and TypeScript Chevron down icon Chevron up icon
Chapter 15: From an Idea to a Working Project – Frontend Integration with GraphQL and TypeScript Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela