How I Set Up My First GraphQL Server API Using Express and Nodejs.

How I Set Up My First GraphQL Server API Using Express and Nodejs.

Β·

7 min read

Hi πŸ‘‹, it's been a while since you heard/read from me, well, I've been learning quite a few new skills to add to my skill set. And like I always do, of course, I'd share them with you.
Here's what to expect from this article.

  • Why I decided to learn GraphQL.

  • How I set up my GraphQL Server.

  • How GraphQL is different from RESTful API

  • Conclusion.

Let's dive right in, shall we?

Why I decided to learn GraphQL.

It is said that you don't appreciate the level of your skill or even feel the need to upskill when there is no form of reward or incentive from your current skill set. Based on this popular parlance I began job-hunting last month(February). While scamping around for jobs, I saw quite a few that fitted my skill set at the time but, they always seemed to have so many applicants. It became clear to me that "If all the applicant's resumes looked alike and had the same skill set in it, it then becomes very hard to decide who the right pick for the company is". I hate leaving anything to luck, so I decided I was going to learn something extra that gives me an edge as a backend node.js developer. I started researching what companies need from a backend developer and technologies to achieve them asides from the ones I had already. As expected I saw quite a few; GrapQL being one of them. This holistically summarizes how I began my journey of learning how to use/set up a GrapQL server. I'd make another article regarding some other projects/skills I've picked up in my subsequent article.

You should follow my blog here on hashnode and turn on the notifications to get notified when I publish another article..... I'd appreciate that.πŸ™

How I Set Up My GrapQL Server.

Since GraphQL is a powerful query language and runtime that allows developers to build APIs with more flexibility and efficiency, I decided to learn it, to boost my efficiency in building APIs. In this article, we will go through the steps to set up a basic GraphQL server using Node.js and Express.

  1. Set Up the Project.

    First, we create a new Node.js project and install the necessary dependencies. We can do this by running the following commands in the terminal:

mkdir Graphql-App
cd Graphql-App
npm init -y
npm install express graphql express-graphql

The above block of code will create a new directory called Graphql-App, initialize a new package.json file, and install the required dependencies: express, graphql, and express-graphql.

  1. Define the GraphQL Schema.

    The next step is to define the GraphQL schema. The schema defines the types and queries that our GraphQL server will support. We can create a new file called server.js inside the server file we create our express app and also define our schema as follows:
    Hint: Populate your server.js file with the code below.

const express = require('express')
const expressGraphQL = require('express-graphql').graphqlHTTP
const {GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql')
const app = express()

const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'HelloWorld',
        fields: () => ({
            message: {
                type: GraphQLString,
                resolve: () => 'Hello World'
            }
        })
    })
})
// GraphQL configuration
app.use('/graphql', expressGraphQL({
    schema: schema,
    graphiql: true
    })
)
// Home route
app.get('/', (req, res) => {
    res.send('Hello World!')
    }
)
app.listen(3000, () => {
    console.log('Server is running on port 3000')
    }   
)

This defines a simple schema with one query field called Hello World The next thing I did there was to define the resolver function(which is a callback). Resolver functions are responsible for resolving queries against the schema. In this case, we only have one query field, so we only need one resolver function., which returns a string "Hello, world".

Now we've set up an Express server that listens on port 3000 and connects it to our GraphQL schema and resolver. We also enable the graphiql IDE by setting the graphiql option to true.

N/B : Notice that the name property in the code above has no whitespace between the 'HelloWorld'. I'm sure you almost missed that.😎

  1. Test the GraphQL Server.

    Now that our server is up and running, we can test it by sending a GraphQL query to the server. We can do this using a tool like Postman or cURL, or the way I did mine by opening the GraphiQL IDE in our browser by navigating to `localhost:3000/graphql`

    Opening the URL sends a POST request to the /graphql endpoint with a JSON payload containing the hello world query. The server responds with a JSON object containing the result of the query:

    You should see an image like the one belowπŸ‘‡

    GraphiQL IDE displaying result on the browser.

    Alternatively:
    To test our hello world query, open a new terminal window and run the following command:

curl -X POST -H "Content-Type: application/json" -d '{"query": "{ hello world }"}' http://localhost:3000/graphql

At this point, I can say congratulations because you have just set up your first GraphQL server using Node.js and Express! You can now customize the schema and resolver to fit the needs of your application(of course I'm assuming yours is different), and add more functionality as required. CiaoπŸ₯‚!

How GraphQL is different from RESTful API.

I'm sure by now(if you carefully followed the steps till this point) you'd agree with me that GraphQL is also a way of building APIs. The truth remains that GraphQL and REST are both popular API design paradigms, but they differ in several key ways which we'd be closely analysing based on what APIs are known for.

  1. Error Handling: Error handling is an important part of a backend developer's tasks. In REST, errors are typically indicated by HTTP status codes, such as 404 (Not Found) or 500 (Internal Server Error). In GraphQL, errors are returned in the response payload as a list of error objects that include a message, a path, and other details about the error.

  2. Response Structure: When requests are made to an endpoint a response is expected both in a REST and GraphQL API. However, in REST, the server determines the structure of the response, which often includes all fields of the resource regardless of whether the client needs them. In GraphQL, the client defines the shape of the response by specifying the fields and data it requires in the request. Hence why some developers argue that GraphQL is more specific in response return.

  3. Data Fetching: Difference exists when it comes to fetching data. In REST, each endpoint typically represents a specific resource, and the client sends HTTP requests to retrieve or manipulate that resource. This is different for GraphQL, in GraphQL, the client sends a single request to the server that specifies the data it needs, and the server responds with only the requested data.

  4. Caching: REST APIs typically use HTTP caching mechanisms to improve performance, such as the ETag header and Last-Modified header. In GraphQL, the server does not send caching headers by default because the response can be different for each request, depending on the fields requested by the user.

  5. Versioning: When it comes to REST APIs, versioning is important to manage changes in the API over time. This is because each version may have different endpoints, response structures, and behaviours. In GraphQL, versioning is not necessary because clients can specify the exact data they need regardless of the server's implementation details or version.

  6. Tooling and Development Experience: GraphQL has a strong type format and a well-defined query language more like SQL, which makes it easy to generate documentation, validate queries, and provide autocomplete suggestions for developers. But REST APIs are more flexible and can be implemented using a variety of programming languages and frameworks, yet they do not provide the same level of tooling and development experience as GraphQL.

Conclusion.

In summary, GraphQL provides a more flexible and efficient way to fetch data than REST, but it requires a different way of thinking about APIs and may not be the best choice for all use cases. Ultimately, the choice between GraphQL and REST depends on the specific requirements of your application and the trade-offs you are willing to make.

Β