Graphql | Manvi Sharma

Post

Graphql

GraphQL is an API query language and a runtime on the server side that executes queries using a user-defined type system for data manipulation. Unlike being dependent on a particular database or storage engine, GraphQL relies on your pre-existing code and data as its foundation.

Graphql vs REST API

When comparing GraphQL and REST API, it's important to understand that they are both approaches for building and consuming APIs, but they have different design principles and characteristics. Here's a comparison between the two:

Data Fetching Efficiency:

REST: REST APIs typically follow a fixed structure where each endpoint represents a specific resource or collection of resources. When fetching data, REST APIs return fixed data structures, which can result in over-fetching or under-fetching of data.

GraphQL: GraphQL allows clients to specify the exact data they need using a single flexible endpoint. It enables efficient data fetching by eliminating over-fetching and under-fetching. Clients have control over the shape and structure of the data they receive

Request Structure:

REST: REST APIs use different HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources. Each endpoint represents a specific operation and can have different request formats.

GraphQL: GraphQL APIs use a single endpoint, and all requests are made using the HTTP POST method. The structure of the request is defined by the GraphQL query language, which allows clients to specify the desired data and operations in a hierarchical manner.

Versioning and Evolvability:

REST: REST APIs often require versioning to introduce changes to the API structure or behavior. This is done by adding version numbers to the endpoint URLs.

GraphQL: GraphQL APIs are inherently versionless. The flexibility of GraphQL's type system allows adding or deprecating fields without breaking existing clients. This promotes a more evolutionary approach to API development.

Network Efficiency:

REST: REST APIs may suffer from over-fetching or under-fetching of data, resulting in additional network requests or data duplication.

GraphQL: GraphQL reduces the number of network requests by allowing clients to specify their data requirements upfront. This minimizes the amount of data transferred over the network, resulting in improved efficiency.

Client Experience:

REST: REST APIs require clients to make multiple requests to different endpoints to fetch related data. This can lead to over-fetching or chaining of requests.

GraphQL: GraphQL provides a more intuitive and seamless experience for clients. Clients can fetch all the required data in a single request, eliminating the need for multiple round trips.

Ecosystem and Tooling:

REST: REST APIs have been around for a long time and have a mature ecosystem with a wide range of tools and libraries for development, documentation, and testing.

GraphQL: Although GraphQL is relatively newer, it has gained significant popularity and has a growing ecosystem. There are various tools and libraries available for different programming languages and frameworks.

Ultimately, the choice between GraphQL and REST API depends on the specific requirements of our project. REST APIs are well-suited for simple, resource-centric APIs, while GraphQL shines in scenarios where flexibility, efficiency, and client-driven data fetching are crucial.

Creating A Basic GraphQL Server With Express

Setup:

For setting we will follow basic commands:

mkdir gql-server // creating a directorynpm init //initailaizing package.jsontouch server.js //entry file where we will make our graphql servernpm install graphql express express-graphql —save //required packages

Creating server:

Add the following code in server.js file:

const express = require("express");const { graphqlHTTP, getGraphQLParams } = require("express-graphql");app.use( "/graphql", graphqlHTTP({ graphiql: true, }));app.listen(5000, () => console.log("Express GraphQL Server Now Running On localhost:5000/graphql"));

This will start our server at port 5000 but at the endpoint /graphql, it will throw an error that the schema is not specified because graphql always needs a schema to run.

Let's add a schema

So schema in graphql needs queries and mutations, Queries return data and Mutations handle adding, and updating data.

Update the following code to the server.js file:

const express = require("express");const { graphqlHTTP, getGraphQLParams } = require("express-graphql");const { GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLList, GraphQLInt, GraphQLNonNull,} = require("graphql");const app = express();const books = [ { id: 1, name: "This1", authorId: 1 }, { id: 2, name: "This1", authorId: 2 }, { id: 3, name: "This1", authorId: 1 }, { id: 4, name: "This1", authorId: 1 }, { id: 5, name: "This1", authorId: 2 }, { id: 6, name: "This1", authorId: 2 }, { id: 7, name: "This1", authorId: 3 }, { id: 8, name: "This1", authorId: 3 },];const authors = [ { id: 1, name: "This1", }, { id: 2, name: "This1", }, { id: 3, name: "This1", },];// Simple Query Schema// const schema = new GraphQLSchema({// query: new GraphQLObjectType({// name: "HelloWorld",// fields: () => ({// message: {// type: GraphQLString,// resolve: () => "Hello World",// },// }),// }),// });const BookType = new GraphQLObjectType({ name: "Book", description: "This represents a book written by an author", fields: () => ({ id: { type: GraphQLNonNull(GraphQLInt) }, name: { type: GraphQLNonNull(GraphQLString) }, authorId: { type: GraphQLNonNull(GraphQLInt) }, author: { type: AuthorType, resolve: (book) => { return authors.find((author) => author.id === book.authorId); }, }, }),});const AuthorType = new GraphQLObjectType({ name: "Author", description: "This represents a author of a book", fields: () => ({ id: { type: GraphQLNonNull(GraphQLInt) }, name: { type: GraphQLNonNull(GraphQLString) }, books: { type: GraphQLList(BookType), resolve: (author) => books.filter((book) => book.authorId === author.id), }, }),});const RootQueryType = new GraphQLObjectType({ name: "Query", description: "Root Query", fields: () => ({ books: { type: new GraphQLList(BookType), description: "List of all books", resolve: () => books, }, authors: { type: new GraphQLList(AuthorType), description: "List of all Authors", resolve: () => books, }, }),});const schema = new GraphQLSchema({ query: RootQueryType,});app.use( "/graphql", graphqlHTTP({ graphiql: true, schema, }));app.listen(5000, () => console.log("Express GraphQL Server Now Running On localhost:5000/graphql"));

This is a basic example of working queries in a graphql server.

Some basic modules provided by graphql:

GraphQLSchema: Represents the schema definition of a GraphQL API, including the available types, fields, and operations.

GraphQLObjectType: Defines an object type in GraphQL, specifying its fields and their types.

GraphQLString: Represents the built-in scalar type for string values in GraphQL.

GraphQLList: Represents a list type in GraphQL, indicating that a field can return an array of values.

GraphQLInt: Represents the built-in scalar type for integer values in GraphQL.

GraphQLNonNull: Represents a non-null type modifier in GraphQL, indicating that a field must have a non-null value.

Some basic modules provided by express-graphql:

graphqlHTTP: A middleware function for Express or Connect that allows you to serve a GraphQL API over HTTP. It handles the execution of GraphQL queries and mutations and provides a convenient way to integrate GraphQL into your server.

getGraphQLParams: A function that extracts and parses the GraphQL parameters (query, variables, operation name) from an HTTP request. It is typically used within server implementations to retrieve and process the GraphQL parameters before executing the query.

That's all the basic you need to know for creating a server in graphql.


Tagged users
editor-img
Divyansh Rai
@divyanshrai
Software Engineer @GlueLabs