Develop GraphQL Web APIs using Apollo Server

I've been learning GraphQL since it is more flexible than REST APIs. GraphQL has been initially developed and used by Facebook in 2012. In 2018, the GraphQL project was moved to the GraphQL foundation (under the Linux Foundation).

Compared to REST, I guess one obvious and major advantage which I've really loved so far is the ability to only retrieve data fields you need for your application.

There are a few interesting frameworks you can start with when building your GraphQL APIs. If you want to build from scratch, you can choose from these 3 server frameworks that I know of.

Apollo Server
https://apollographql.com/docs/apollo-server

Express GraphQL Server
https://github.com/graphql/express-graphql

Prisma
https://www.prisma.io/with-graphql

I've chosen Apollo for this example since Apollo is one of the pioneers in the GraphQL space.  Also, the code is very simple. In this example, we'll be using NodeJS. I am using node v11.4.0 for this example. So here it goes...

All source code for this example is available in my github repo.
https://github.com/donvito/graphql-server-apollo-example

The first thing you need to do is initialise our node project and install dependencies we need.

npm init --yes && npm install apollo-server graphql

Create an index.js, this will be our node application's entry point. Then, add the Apollo and gql APIs from the apollo-server package.

index.js

const { ApolloServer, gql } = require('apollo-server');

Next, we need to define the type definitions which is required to run the Apollo server. Type definitions describe the data for your API and how applications can query your data. In this example, I created a Job type which represents the structure of the data I wish to return from the API. I also defined 2 queries, one for querying all jobs and another for querying a single job based on it's id.

const typeDefs = gql`
  type Job {
    id: Int
    position: String
    company: String
    description: String
    location: String
    employmentType: String
    skillsRequired: [String]
  }

  type Query {
    job(id: Int!): [Job],
    jobs: [Job]
  }
`;

For simplicity, I just created an array of jobs data. As you get more experience, you can replace this array with data coming from a database or a REST API call.

const jobs = [
  {
    id: 1,
    position: 'Software Engineer',
    company: 'Apple',
    description: 'job description',
    skillsRequired: ['Go', 'GraphQL'],
    location: 'location',
    employmentType: 'full-time',
  },
  {
    id: 2,
    position: 'Software Engineering Manager',
    company: 'Google',
    description: 'job description',
    skillsRequired: ['Scrum', 'JIRA'],
    location: 'location',
    employmentType: 'full-time',
  },
];

Now, let's create a function which will return the data when an id is passed as an argument in the query. This function basically filters the array based on the job's id as the filter criteria. We'll use this later when we define our resolvers.

var queryJobs = (jobId) => {
  return jobs.filter((job, index, filteredArray) => {
        return job.id == jobId
  });
}

Next, let's define our resolvers.  We have 2 resolvers in this example.

The first one is to accept queries wherein an id is passed.

 job: (parent, args, context, info) => {
      return queryJobs(args.id) 
 }

The second resolver is simply returning all jobs.

jobs: () => jobs

Here's the complete code for the resolvers. Resolvers define the way how data is going to be returned by the Queries defined in our type definitions.

const resolvers = {
  Query: {    
    job: (parent, args, context, info) => {
      return queryJobs(args.id) 
    },
    jobs: () => jobs
  },
};

That's it, we can now run the Apollo Server.

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

We now have everything required for our GraphQL server. If you are not able to follow, all source code is available in github. You can now run the server by executing this command in your terminal.

$ node index.js

Once the server is up and running, you'll see a server is ready message.

Access the GraphQL Playground for our API in http://localhost:4000

You can try the ff. queries we implemented earlier in our code. You can paste it into the left section of the GraphQL Playground.

Query 1: All jobs

{ 
  jobs {
    id
    position
    company
    description
    location
    employmentType
    skillsRequired
  }
}

Query 2: Job by id

{ 
  job(id: 2) {
    id
    position
    company
    description
    location
    employmentType
    skillsRequired
  }
}

That's it! We have fully implemented a basic GraphQL server using Apollo.

All source code is available in my github repo.
https://github.com/donvito/graphql-server-apollo-example

Try out the GraphQL playground in Glitch
https://donvito-graphql-server-apollo-example.glitch.me/

You can also remix the code in glitch.
https://glitch.com/~donvito-graphql-server-apollo-example

Cheers! Hope this helps anyone who is starting out with GraphQL!

For more updates my new blog posts, you can follow me in Twitter @donvito and GitHub.  I also share code in my GitHub. If you want to know more about what I do, please add me in LinkedIn. I recently started a new youtube channel - I upload some tutorials there as well. Check it out!

I'm also looking for remote and contractual software development projects.
http://www.melvinvivas.com/looking-for-remote-software-development-work-outsource/