Tutorial — Writing Your First GraphQL API

What is GraphQL?

Getting Started

Directory Structure

The Data

module.exports = [
{name: "Sparky", age: 5},
{name: "Spot", age: 5},
{name: "Snookems", age: 5},
{name: "Fluffy", age: 5},
{name: "Clifford", age: 5},
{name: "Benji", age: 5},
{name: "Charlie", age: 5},
{name: "Michelle", age: 5},
{name: "MooShu", age: 5},
]

Our typedefs

const { gql } = require("apollo-server");// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
######################################
# Define Data Types Below
######################################
type Dog {
name: String,
age: Int
}
######################################
# Define Input Types Below
######################################
input newDog {
name: String,
age: Int
}
#######################################
# Define all your Query Resolvers Below
#######################################
type Query {
dogs: [Dog]
}
#######################################
# Define Mutations Below
#######################################
type Mutation {
addDog(input: newDog): [Dog]
}
`;
module.exports = typeDefs;

Define Our Query and Mutation

const dogs = require("../models/dogs");const resolvers = {
Query: {
dogs: (parent, args, ctx, info) => dogs,
},
Mutation: {
addDog: (parent, args, ctx, info) => {
dogs.push(args.input);
return dogs;
},
},
};
module.exports = resolvers;

Testing the API

{
dogs{
name
age
}
}
mutation{
addDog(input:{
name: "Peachy"
age: 5
}){
name
age
}
}

On the frontend, can I use fetch

fetch('https://127.0.0.1:4000', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: '{
dogs{
name
age
}
}' }),
})
.then(res => res.json())
.then(res => console.log(res.data));
fetch("http://127.0.0.1:4000", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `mutation{
addDog(input:{
name: "Peachy"
age: 5
}){
name
age
}
}`,
}),
})
.then((res) => res.json())
.then((res) => console.log(res.data));

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store