Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Types in GraphQL
Next article icon

What is GraphQL?

Last Updated : 01 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Client and server communication follows a traditional approach of REST APIs which is good but nowadays applications have become more powerful and complex which requires a more flexible approach rather than REST, so here GraphQL comes into the picture. In this article, we will go through all the concepts of graphQL.

What is GraphQL?

GraphQL is an open-source data query language for APIs and It is a server-side runtime for executing the query. The server's GraphQL runtime takes care of executing the query and ensuring that the right data is fetched and sent back.

It is an alternative to REST, where clients make multiple requests to different endpoints to get the data they require but in GraphQL clients can request exactly the data they need in a single query.

It was developed by Facebook and made open source for the whole world.

Example: Let's take an example, Suppose We have a REST API for a blog. If we want to get a blog post and its author information then We have to make two separate requests to the server:

  1. one for the blog post.
  2. another for the author's details.

But In GraphQL, we will request both in one query and It will reduce network overhead.

Key Features of GraphQL

GraphQL has several features that set it apart from traditional REST APIs, offering developers a more flexible and efficient way to manage data. Let's explore these features as follows:

  1. Flexible Queries: Clients can request exactly the data they need, avoiding over-fetching and under-fetching.
  2. Strongly Typed: GraphQL schemas provide clear data structures and types, reducing runtime errors.
  3. Real-time Updates: GraphQL supports subscriptions for real-time data interactions.
  4. Single Endpoint: Unlike REST, GraphQL typically uses a single endpoint for all data requests.
  5. Introspection: Clients can explore the schema's capabilities through introspection queries.
  6. Batching: Multiple queries can be sent in a single request to minimize network overhead.
  7. Efficient for Mobile: GraphQL can be more efficient for mobile devices by reducing data transfer.
  8. Versioning: It eliminates the need for versioning in APIs, as changes can be made without breaking existing clients.

Key Components of GraphQL

For Better Understanding of GraphQL, let's see some key components of GraphQL which are as follows:

1. Schema

It defines the data types that can be queried and their relationships. GraphQl uses it's own language that is Schema Definition Language (SDL) for writing the schema. It is human readable language and It does not depends upon any specific language or framework. Schemas has two main types:

  1. Queries (for retrieving data)
  2. Mutations (for modifying data).

2. Types

GraphQL defines custom types to define the structure of data. There are two main types of Type:

  • Scalar Types: It represent values like integers, strings, booleans, and floats.
  • Object Types: It represent complex objects with fields. Fields can be scalars or other object types. For example, A "User" object type with fields like "id", "name", and "email".

3. Queries

It is used to retrieve data from a GraphQL server. It specify what type of data we want to retrieve from fields of which types. It is similar to GET requests in REST APIs but allow to request exactly the data we need. It is reducing over-fetching or under-fetching.

4. Mutations

It is used to modify data on the server. It can be used for creating, updating, or deleting data. Mutations are similar to POST, PUT, or DELETE requests in REST APIs.

GraphQL basic Schema Design

let's take an example to understand the basics of graphQL Schema design

Example:

type Book {

id: ID!

title: String!

author: String!

}

type Query {

books: [Book!]!

book(id: ID!): Book

}

type Mutation {

createBook(title: String!, author: String!): Book

updateBook(id: ID!, title: String, author: String): Book

deleteBook(id: ID!): Boolean

}

Explanation:

We have defined three main types:

  • Book
  • Query
  • Mutation

Book Type:

The Book type represents a book object with three fields:

  • id: An ID field, which is non-nullable (! indicates that it cannot be null).
  • title: A String field, which is non-nullable.
  • author: A String field, which is non-nullable.

Query Type:

It defines two query fields:

  • books: Returns a list of Book objects, ! indicates a non-null list of non-null Book objects.
  • book(id: ID!): Takes an id argument and returns a single Book object.

Mutation Type:

It defines three mutation fields:

  • createBook: Creates a new book with title and author arguments and returns a Book.
  • updateBook: Updates an existing book with id, title, and author arguments and returns a Book.
  • deleteBook: Deletes a book with the given id and returns a Boolean indicating success.

Conclusion

GraphQL is a powerful and flexible data query language for APIs. It is offering a more efficient alternative to traditional REST APIs. It allows clients to request exactly the data they need and reducing network overhead. It provides features like strong typing, real-time updates, and a single endpoint.


Next Article
Types in GraphQL

K

kumarsar29u2
Improve
Article Tags :
  • Geeks Premier League
  • GraphQL
  • Databases
  • GraphQL
  • Geeks Premier League 2023

Similar Reads

    Why Use GraphQL?
    GraphQL is the query language for the Application Programming Interfaces (APIs). It provides a complete description in your API so that the necessary information will get fetched. It provides power to clients to ask for exactly what they need and nothing more. In this article, we are going to look a
    8 min read
    What is GraphQL Queries
    GraphQL is a powerful open-source Query Language for APIs. It is most commonly known for its single endpoint query which allows the user to define a single endpoint to fetch all the information needed. Queries in GraphQL allow us to retrieve the data from an API endpoint, and the data is what we spe
    4 min read
    Schema in GraphQL
    GraphQL is a powerful open-source Query Language for APIs. It is most commonly known for its single endpoint query which allows the user to define a single endpoint to fetch all the information needed. Schemas in GraphQL are the blueprints for its APIs and define what the request-response structure
    5 min read
    Types in GraphQL
    GraphQL is a strongly typed query language used as a manipulative language for various APIs. It is also called a query language for APIs. GraphQL also helps to describe our data. GraphQL services can run in any language In this, Types are the fundamental concepts that define various data types prese
    4 min read
    Mutations in GraphQL
    GraphQL is a query language for REST APIs created by Facebook which is designed to provide more efficiency, flexibility, and superiority in data handling. While GraphQL queries are used to retrieve information, mutations are used to perform data operations on the server, similar to HTTP Commands lik
    6 min read
    GraphQL Validation
    GraphQL validation is an important step in ensuring the integrity and correctness of GraphQL queries and mutations. It involves checking the syntax, structure, and semantics of GraphQL documents to identify any errors or inconsistencies before executing them against a GraphQL server. In this article
    4 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences