Build server APIs with GraphQL and Express #2: GraphQL Schema and Create APIs from JSON data

in #utopian-io5 years ago (edited)

Repository

https://github.com/graphql

What Will I Learn?

  • GraphQL Schema
  • Create APIs from JSON data

Requirements

  • Basic Javascript
  • Install Node
  • Install Express
  • Install GraphQL

Resources

Difficulty

Basic

Tutorial Content

Hi everyone, this tutorial will continue our learning about GraphQL, this is the second series of tutorials that we have gone through. so for those of you who are new to or don't know about GraphQL, then you can visit the official GraphQL website or follow the previous tutorial here, In the previous tutorial we have set up and made a server on the application that we made, now in this tutorial we will discuss more about GraphQL. okay, we just start our tutorial.

GraphQL Schema

Schema is a familiar method when we want to build a database. schema is often intended as a blueprint of a database structure or table. but there are different concepts applied to GraphQL. In the previous tutorial, we got an error when we will access the GUI from GraphQL as shown below:

Screenshot_16.png

We get this error because we don't have a schema, an interface from GraphQL must have a schema. therefore we can make the schema like the example below:

app.js

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express()

let schema = buildSchema(`
    type Query {
        name : String
    }
`)
app.use('/graphql', graphqlHTTP({
    schema: schema,
    graphiql : true // To set GUI For testing
}))

app.listen(4000, ()=> console.log("Running on port 4000..."));

To create a schema we can use the functions we have imported from the graphql library and we have defined it in the previous tutorial like this const { buildSchema } = require('graphql');.

After importing the function we can use it in the following way buildSchema(). We can wrap the schema inside the buildSchema() function with backtick.

Then define the type is the query and the key is defined along with the data type name: String. Well, we created the schema and defined it in the variable let schema. Now we can register the schema in the API GUI that we have created before.

app.use('/graphql', graphqlHTTP({
    schema: schema,
    graphiql : true // To set GUI For testing
}))

Well, if there is no error then we can see the results as shown below:

ezgif.com-video-to-gif (1).gif

Now we have successfully displayed the interface to start the develop API process. but we can see in the picture above that we get a return null, this happens because we do not give a return in routing '/ graphql'.

  • Return rootValue

In this section we will learn to respond to values by using the rootValue key. in this key we can pass the response on that route. for more details, we can see the code below:

app.js

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express()

let schema = buildSchema(`
    type Query {
        name : String
    }
`)

let callMyName = {
    name: ()=> 'Millea duski'
}
app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: callMyName,
    graphiql : true // To set GUI For testing
}))

app.listen(4000, ()=> console.log("Running on port 4000..."));

Here I will create a let callMyName variable with a key name and its value is a function that returns my name which is "Millea Duski" name: ()=> 'Millea duski'. I will then register this variable in the rootValue key in graphqlHTTP. If our code runs well, we will see the response as shown below:

ezgif.com-video-to-gif (2).gif

We can see in the picture above we have succeeded in creating an interface that is used to test the GraphQL API. In the next section, we will learn to create a GraphQL API from the data of array.


- Create APIs from JSON data

Here we will learn new things in GraphQL, here we will learn how to display API data that comes from JSON data. Of course, there are differences when we will create a GraphQL API using JSON data. Here I will create JSON data as an example that we can use. For more details, we can see the example below:

app.js

let Forums = [
    {id: 1, title: "This the first Title of Forum", desc: "This the first Description from the first forum"},
    {id: 2, title: "This the second Title of Forum", desc: "This the first Description from the second forum"},
    {id : 3, title: "This the Third Title of Forum", desc: "This the first Description from the Third forum"}
];

The data above is the data that we will use in our application. well, what we need to do is define the structure of the schema that we will use. We store the data in a variable let Forums. In this JSON data has a key id, title, and desc.

  • Defined Schema

In this section, we can define the Schema that we will use by using ForumsData. Here I will make schema with the name Forum. For more details, we can see the example below:

Schema Forum

let schema = buildSchema(`
    type Forum {
        id : ID,
        title : String,
        desc : String
    }
    type Query {
        forums : [Forum]
    }
`)

Here I will create a Forum schema with a key id data ID type, title and desc with a data type String. Well after we define the Forum scheme then we have to define it in the Query type. as we can see below:

type Query {
        forums : [Forum]
    }

We enter the Forum in the form of an array [] because we know that the results will be in the form of a list, so we can use Arrays [Forum]. After this section is finished, the next task is to make resolvers.

  • Make Resolvers

Well now we will get acquainted with resolvers, resolvers have to accept and draw data that we will display on the Graphiql interface. To be more complete and more clearly we can see in the code below:

app.js

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express()
// Create JSON data
let ForumsData = [
    {id : 1, title: "This the first Title of Forum", Desc : "This the first Description from the first forum"},
    {id : 2, title: "This the second Title of Forum", Desc : "This the first Description from the second forum"},
    {id : 3, title: "This the Third Title of Forum", Desc : "This the first Description from the Third forum"}
];
// Create schema
let schema = buildSchema(`
    type Forum {
        id : ID,
        title : String,
        desc : String
    }
    type Query {
        forums : [Forum]
    }
`)
//Create resolvers
let resolvers = {
    forums: ()=> ForumsData
}

app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: resolvers,
    graphiql : true // To set GUI For testing
}))

app.listen(4000, ()=> console.log("Running on port 4000..."));

Well, we can see in the example above we have a resolvers that will bring up data that tastes from ForumsData, ForumsData is a variable that we have defined to store JSON data let ForumsData. For more details we can run the application that we created, to see the results whether we managed to create a list of data from JSON.

ezgif.com-video-to-gif (3).gif

We can see in the picture above we have succeeded in creating a list of data from the GraphQL API, now we need to pay attention we must change the value of the rootValue with the variable resolvers rootValue: resolvers. So graphqlHTTP can display the value of resolvers. thank you for following this tutorial, hopefully, it will be useful for you.

Curriculum

GraphQL and Express #1

Proof of work done

https://github.com/milleaduski/api-graphql

Sort:  

Thank you for your contribution.
This is definitely an interesting topic to tackle. We enjoyed reading through it.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @mcfarhat! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.25
TRX 0.20
JST 0.035
BTC 95284.46
ETH 3462.33
USDT 1.00
SBD 3.49