GraphQL returning data by Id

Hi in this post we are going to learn how to return specific data by given an Id.

If you want to read the last post please click here GraphQL fetching data in the client

Now if we click a job:

This is going to redirect us to see this specific job details, now if you see the url have the job Id and also is giving us an error that means that this specific Id can be founded:

So, we need to declare another field into the GraphQL schema in order to show a specific Job.

Open the schema.graphql and add another field called Job and for this field we need to specify which job with a specific Id (as the url requirement)

So in GraphQL we can pass arguments to a query using this syntax, this means that in order to get specific job we need to set an id and that id is type ID and also it couldn’t be null (!)

job(id: ID!)

Finally we need to declare the return type of this field, so in this case our type need to be a Job:

job(id: ID!): Job

The entire file will look like this:

type Query {
  job(id: ID!): Job
  jobs: [Job]

type Company {
  id: ID!
  name: String
  description: String

type Job {
  id: ID!
  title: String
  description: String
  company: Company

Ok, the next step is write a resolver for this job field, open the resolvers.js file and add the next resolver to get the data of that specific job id:

// Data
const db = require("./db");

const Query = {
  // Job return specific job given an Id
  job: (root, args) =>,
  // Jobs resolver that return an array of jobs
  jobs: () =>,

const Job = {
  company: (job) => db.companies.get(job.companyId),

module.exports = { Query, Job };

Nice, now if we try this query in our Playground we can see that our query by Job Id works as we want:

All this configuration is working in server side (schemas & resolvers), next step is work in client side to create a function that execute that query in client (as we did in last post)

By Cristina Rojas.