
Before starting, I am assuming that you have an idea about expressJS and its functionality. In this article, we are going to see how to use GQL with ExpressJS. mean how to integrate GraphQL in expressJS apis. Btw, it's not compulsory to use GQL with ExpressJS; we can use GQL independently as well. There is no problem with it.
GQL has its own functionality to handle whole-api queries. But if we have a project that contains lots of API requests and also has a lot of traffic and data transfer, then GraphQL can be used to optimize your application's performance by replacing API requests, which increases unnecessary bandwidth.
What is ExpressJS ?
ExpressJS is a nodeJS backend framework that is used to code server-side applications. Also, by using expressJS, we can make REST APIs very easily.
What is GraphQL?
GraphQL is an alternative to Rest APIs. There are mainly two problems with REST APIs.
1. Over fetching
2. Making separate apis for every single (fetch data) request.
3. Which is not good for performance optimizations.
Why to use GQL with expressJS ?
If you have already designed the backend with expressJS, which has lots of API requests and logic, then you can integrate GQL into it very easily with the help of express middleware.
Note that we are not replacing the functionality of ExpressJS with GQL here. We are just adding the GQL so that we can make use of both simultaneously.
Github code: https://github.com/sanketmhaiske/express.js-with-GraphQL
There is no need to replace the whole backend if you have the backend written in ExpressJS. Just to add some extra code, we can use both GQL and Express simultaneously.
Let's see how it works.
For GraphQL api requests the request path will be your_domain/graphql— and for expressJS api request your_domain/request_name
Integration
For detail info you can visit https://www.apollographql.com/docs/apollo-server/api/express-middleware
Install necessary packages.
For GQL queries will will have to define schema and resolvers
GQL schema
GQL resolver
Creating ExpressJS Server
Github Ref: https://github.com/sanketmhaiske/express.js-with-GraphQL