DEV Community

Cover image for How to setup Local GraphQL API
Vishang
Vishang

Posted on

4 3

How to setup Local GraphQL API

Requirements

nodejs
babel

Assume that you already have Node js installed in your system.

Create a folder i.e graphql-local-server

initialize package.json with following command. we just keep all defaults with it.

npm init

Add a start script to your package.json file

{
"name": "graphql-local-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0"
}
}
view raw package.json hosted with ❤ by GitHub

Setup babel

Install babel dependencies.

Run following commands in order to install latest version of babel compiler and babel preset

npm install babel-cli babel-preset-env

babel-cli is a babel compiler and babel-preset-env will tell babel what it should change so the browser can understand the JS code.

Now create a single file called .babelrc in your root folder which will tell our presets which environment to use.

{
"presets": [
"env"
]
}
view raw .babelrc hosted with ❤ by GitHub

import GraphQL-yoga library

Official documentation

npm install graphql-yoga

create an index.js file inside your src root folder with following content.

import { GraphQLServer } from 'graphql-yoga'
//Type definations (Application Schema)
//Describes the operations and the data structures.
const typeDefs = `
type Query {
hello: String!
}
`
//Resolvers object for our API
// These are the functions that acutally run when various oprations are performed.
const resolvers = {
Query: {
hello() {
return "Hello World!"
}
}
}
const server = new GraphQLServer({
typeDefs,
resolvers
})
server.start(()=>{
console.log('The Sever is up!')
})
view raw index.js hosted with ❤ by GitHub

Now when you run

npm run start

you will see the log with "The server is up!" text.

By default, graphql-yoga starts the server on port 4000

Open the http://localhost:4000/ to see your first graphQL api.

Your first available GraphQL query

query {
hello
}

Folder Structure

Folder Structure

Retry later

Top comments (1)

Collapse
 
sssangha90 profile image
Sukh Sangha

Thank you