Flutter with GraphQL : Part 1 Introduction to GraphQL

Debasmita Sarkar
10 min readJul 1, 2024

--

Picture this:
You are in McDonald’s and you ordered a burger without tomato.
Now you expect a burger without tomato, right?
What if the server hands you the burger and guess what?! There is a freaking tomato in it!!!!
So irritating right?

Now, what if the server remembered what you asked and gave you the burger without tomato. Won’t that be amazing! You get what you ask.

Hello Peeps! have you ever been in a similar situation with your backend response?
You asked just the username but you got the entire user object with user’s 7 generations history! Just kidding , but it is true though!

Let’s get you what you asked, not a bit more , not a bit less. You get , what you ask!

Welcome to the world of GraphQL, here you will get what you have asked from the server. This series is here to be your trusty sidekick, introducing you to the wonders of GraphQL and showing you how to seamlessly integrate GraphQL into your Flutter applications and more.

Sneak peak into the series

  1. Introduction to GraphQL:
    I’ll start with the basics, covering what GraphQL is and why it’s awesome. You’ll learn the core concepts, how it compares to REST, and the advantages it brings to your projects.
  2. Creating a Flutter Application and Integrating GraphQL: I’ll guide you through setting up a Flutter application and integrating GraphQL. You’ll become familiar with tools like GraphQL client and GraphQL codegen. I’ll also explain the project we’ll be building throughout this series.
  3. Writing Queries and Mutations, Handling Errors, Automatic Cache Updates: In this part, you’ll learn how to write effective GraphQL queries and mutations. I’ll cover how to handle errors gracefully and how to leverage automatic cache updates to ensure your app’s data stays fresh.
  4. Advanced GraphQL Features, Subscriptions and Optimistic UI: Finally, We will dive into advanced GraphQL features like subscriptions for real-time updates and implementing an optimistic UI to enhance user experience by making the app feel faster.

What will you learn in this part?

By the end of part 1,
1. You’ll have leveled up your coding game with a solid understanding of GraphQL fundamentals, its advantages over REST, and the core concepts.

2. But wait, there’s more! I’ll guide you through setting up a simple server to test your queries.

What is 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.

The above is the official definition from GraphQL. But I know like me, it went right above your head too. Let’s talk our language.

For us frontend developers, the concept is very rudimentary when we are dealing with backend generally with REST api.

1. App requests for data from server or wants to modify data via calling a REST Api end.
2. Now, Server gives back a response or error in reply of that request.

To explain a bit more, let’s say I want to create a simple book collection application, so I need REST Api end points to fetch book details and If I want to fetch just the author of the book, I will have to call another end point to get that data.

Now , what changes if the backend uses graphql server?

1. Every requests becomes POST request, instead of GET, POST, PUT or DELETE.
2. You don’t have to call different end points like you did in REST api like api/book?id=1 or api/author?bookid=1 . Instead you will have to write a query. Don’t worry I will explain this later.
3. The query will contain the fields that you need from server. In the first request, we needed book’s id, title, author so the query should look like this.

4. In second request we just needed that particular book’s author’s name, look how the query changes.

This was an overall idea and We will delve into more details of query, mutation and other things soon.

Major components in GraphQL:

There are three major things that I believe you should know about GraphQL right away. They are schema, query and mutation.

1. Schema

The schema is like a blueprint for your data. It defines what data you can ask for, how you can ask for it, and how different pieces of data relate to each other.

Generally before implementing a feature, the backend and the frontend devs agrees on a blue print for the object or response for an end point. For example, in REST, the endpoint api/book?id=1 was returning a book object with several details like id, title and author.

In GraphQL, the blue print for objects is dumped in a file called schema.graphql . In schema, you can find all the object and their fields and how one object is related to other and what kind of queries and mutations are allowed . Typically, the backend dev updates this file.

2. Queries
Queries are how we request data from a GraphQL server. They specify exactly what data we need and in what shape.

In REST, we use GET requests to fetch data. For example, GET api/book?id=1 retrieves the book details.

In GraphQL, Query is sort of equivalent to a GET request. Instead of calling different end points for different set of data, you write different queries to fetch them.

3. Mutations
Mutations are how we modify data on the server. They are similar to queries but are used for creating, updating, or deleting data.

In REST, we use POST, PUT, and DELETE requests to modify data. For example, POST api/book to create a new book, PUT api/book?id=1 to update a book, and DELETE api/book?id=1 to delete a book.

In GraphQL, all the above can be done by writing different mutations.

Now let’s understand how schema, query and mutations work together.

We’ll take that book example again. So in the schema, there are object types: Book and Author. These are the data models that you will be dealing with in the project, and you can see their structure defined in the schema. Additionally, there are Query and Mutation types that define how to fetch and modify these objects:

type Book { 
id: ID!
title: String!
author: Author!
}
type Author { 
id: ID!
name: String!
}

Now, you know what a type is , it’s time to fetch object via Query.
Queries
in our schema let us fetch these objects.

Schema Definition of Query:

  • This is part of the GraphQL schema definition.
  • It defines the structure and types of queries that your GraphQL server can accept.
  • It tells the server what kinds of queries clients are allowed to make and what type of data those queries will return.
type Query { 
book(id: ID!): Book
books: [Book]
author(id: ID!): Author
}
  • The book query allows us to fetch a single book by its ID.
  • The books query allows us to fetch a list of books.
  • The author query allows us to fetch a single author by their ID.

Query Execution:

  • This is an actual query written by the client (frontend developer).
  • It specifies what data the client wants to fetch from the server, using the structure defined in the schema.
  • It includes the specific parameters (like id: 1) and the fields of data requested.
query {
book(id: 1) {
id
title
author {
name
}
}
}
  • This query is sent to the server to fetch data. The server uses the schema to validate and execute this query.
  • The server reads this query, processes it according to the schema, and returns the requested data in the specified format. The below can be a response of this Query
{
"data": {
"book": {
"id": "1",
"title": "GraphQL for Beginners",
"author": {
"name": "John Doe"
}
}
}
}

With the previous example, it is quite obvious that there are benefits of using GraphQL.

Schema Definition of Mutation:

type Mutation {
addBook(title: String!, authorId: ID!): Book
updateBook(id: ID!, title: String, authorId: ID): Book
deleteBook(id: ID!): Book
}
  • Just like query, schema definition of mutation defines the structure and types of mutations that your GraphQL server can accept.
  • It tells the server what kinds of data modifications clients are allowed to make and what type of data those mutations will return.
  • The addBook mutation allows us to add a new book with a title and authorId.
  • The updateBook mutation lets us update an existing book's title and author.
  • The deleteBook mutation allows us to delete a book by its ID.

Mutation Execution:

mutation {
addBook(title: "New Book", authorId: "1") {
id
title
author {
name
}
}
}
  • This is an actual mutation written by the client (frontend developer).
  • It specifies what data the client wants to modify on the server, using the structure defined in the schema.
  • It includes the specific parameters (like title: "New Book" and authorId: "1") and the fields of data requested to be returned after the mutation.

Benefits of using GraphQL:

  • Flexible Queries: You can ask for exactly what you need and nothing more, reducing the amount of data transferred over the network.
  • Faster Development: GraphQL allows frontend developers to iterate quickly and develop without waiting for backend changes.
  • Strongly Typed Schema: GraphQL’s type system ensures that the queries are correct and can be validated by the server, reducing runtime errors.
  • Better Performance: By allowing clients to specify the structure of the response, GraphQL reduces over-fetching and under-fetching of data, leading to more efficient network usage.
  • Easier Evolution: With GraphQL, adding new fields and types to the API doesn’t require any changes to existing queries, which makes it easier to evolve your API without breaking existing clients.

Pheww!!! The hard part is over! Now go grab yourself a coffee and give yourself a well-deserved pat on the back. You’ve just cracked the mystery of GraphQL!
Also if you feel like it,
buy me a coffee!! ☕️

Try Out GraphQL Queries and Mutations

GraphQL adventurers! Ready to put your new skills to the test?
I’ve set up a GraphQL API just for you. The coolest way to explore this API is by using GraphiQL (pronounced “graphical”), a tool from Facebook that makes testing GraphQL queries as easy as pie.

Access GraphiQL
To get started, head over to GraphiQL Online. It’s a nifty tool that connects to your GraphQL endpoint, auto-magically fetches the schema, and provides a user-friendly interface to write and run queries.

  1. Open GraphiQL Online: Go to GraphiQL Online.

2. Set the Endpoint: Enter the URL of GraphQL endpoint: https://graphql-book-server-debo-a1bbf9f7b9f0.herokuapp.com/graphql

3. Start Querying:

  • Write your queries or mutations in the left pane.
  • Click the “Execute” button (the ▶️ icon) to run them.
  • See the results on the right.

Example Queries : Let’s fetch some data!

  1. Fetch a Book by ID:
query {
book(id: 1) {
id
title
author {
name
}
}
}

2. Fetch all books

query {
books {
id
title
author {
name
}
}
}

Example Mutations : Now, let’s change some data.

1. Add a New Book

mutation {
addBook(title: “New Book”, authorId: “1”) {
id
title
author {
name
}
}
}

2. Update a Book

mutation {
updateBook(id: "1", title: "Updated Book Title", authorId: "2") {
id
title
author {
name
}
}
}

3. Delete a Book

mutation {
deleteBook(id: "1") {
id
title
}
}

Feeling adventurous yet? Try out dynamic arguments with variables.
Parameterize Your Query:

query ($limit: Int!) {
books(limit: $limit) {
id
title
}
}

In GraphiQL, scroll to the bottom of the page to find the Query Variables pane. Add your variables there as a JSON object.

{
"limit": 5
}

Summary

  • You’ve leveled up your coding game with GraphQL fundamentals, understanding its advantages over REST.
  • You know how to define schemas, write queries, and perform mutations.
  • You’ve learned the benefits of using GraphQL.
  • You’ve tried out real-world queries and mutations using GraphiQL.

Hello everyone!! I am Debasmita. I fell in love with Flutter a long time ago and I am head over heels now. I am a Senior Mobile Developer at Peggy and Google Developer Expert for Flutter and Dart. Check out recent updates from me in twitter, linkedIn, youtube, github.
If you like this article please give a 👏 or 50 !! Also share your thoughts on comment section. Cheers!! :)
Love my work or feeling generous? 😁 Support me !!

--

--

Debasmita Sarkar

Senior Mobile Developer @Peggy, Flutter Enthusiast, Tech Savvy, Speaker, Artist