Introduction
In this article, I'm going to explain the basics of making a simple query request to an API using GraphQL, and ExpressJs.
We will look at concepts like:
- Making an express server
- Creating our schema
- Testing queries using graphiql.
So first create a folder and give it any name of your choice, I'll name mine simple-graphql-project
Inside your newly created folder, open the terminal and run the command
npm init -y
This will initialize our project with npm so that we can install packages that'll be needed for the tutorial.
Before we start writing the code, let's install all the dependencies we'll be needing for this project.
In your terminal, run the command
npm i express graphql express-graphql lodash axios
or
yarn add express graphql express-graphql lodash axios
Now with all our packages installed, let's write some code:
Create a file named app.js
– this will be our main file
Paste the following code inside the app.js file, then I'll explain what the code means:
const express = require('express')
const {graphqlHTTP} = require('express-graphql')
const schema = require('./schema/schema')
const app = express()
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}))
app.listen(4000, ()=> {
console.log('Started server on port 4000');
})
So, from the code above:
In line 1:
We imported our express package which is our backend framework for node js to create servers and endpoints for our project.
In line 2:
graphqlHTTP
—is a module from express-graphql
that provides a simple way to create an Express server that runs a GraphQL API.
In line 3:
schema file
– this is a file we're yet to create, but I can tell you what this file will contain, in our schema file is where we'll write all the query(ies) we'll make to an API endpoint or an internal JSON file.
For instance, in this query/ies, we will extract the exact data we want to get when we make a call to an API endpoint, and also what kind of data type those data would be.
For example: if we're making a request to get a list of blog posts from an API, we expect that an ID for each post would be returned as part of the data, right? Also, we want to attribute the data type of the ID we're expecting, either it's a string or a number or maybe a boolean value.
fields: () => ({
id: {type: GraphQLString},
flight_number: { type: GraphQLInt },
name: { type: GraphQLString },
details: { type: GraphQLString },
success: { type: GraphQLBoolean },
}),
This is what i meant by that explanation. In this project we will make a request to a SpaceX API and the results we want from the huge chunk of data we will be receiving from the API are: id
of type string
, flight_number
of type int
, name
and details
of type string
and success
of type boolean
.
In line 7-10:
We will pass 2 arguments into our express app function, the first is our endpoint where we will be making all the queries from.
The second argument is graphqlHTTP function which we will pass our schema file containing our query so that express can interact with the GraphQL API, the second parameter graphiql
is the tool we will be using to test our queries.
In line 13-15:
This is the port where we will be starting up our express server from.
So, let's jump into our schema file now, create a folder named schema and create a file inside that folder named schema.js.
Paste the following code inside the schema.js file:
const graphql = require("graphql");
const {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLSchema,
GraphQLList,
GraphQLBoolean,
} = graphql;
const axios = require("axios");
const LaunchType = new GraphQLObjectType({
name: "Launch",
fields: () => ({
id: {type: GraphQLString},
flight_number: { type: GraphQLInt },
name: { type: GraphQLString },
details: { type: GraphQLString },
success: { type: GraphQLBoolean },
}),
});
The first 21 lines of our code contains our import statement statements. Our LaunchType
variable, is a graph object type which will contain the selected fields we want to get from our API call.
Let's continue with the code:
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
launch: {
type: LaunchType,
args: { id: { type: GraphQLString } },
resolve(parent, args) {
return axios
.get(`https://api.spacexdata.com/v5/launches/${args.id}`)
.then((res) => res.data);
},
},
launches: {
type: new GraphQLList(LaunchType),
resolve(parent, args) {
return axios
.get("https://api.spacexdata.com/v5/launches")
.then((res) => res.data);
},
},
},
});
The RootQuery
object will contain 2 queries that we'll be making, firstly we want to get details about a particular launch by passing the id as a query string to the API URL and the second query request is to get details of all the launch that had been made.
So for the first query which is launch
: we passed in a type “LaunchType” and also an “args” which is the argument/query string we will be using to fetch the details for a particular launch detail. In the resolve function we also pass two arguments parent and args, we won't be talking about the parent argument for now. Inside the resolve function, we return the data we get from querying our API endpoint.
The second query which is launches
: if you notice we used a type GraphQLList
because we're getting not just one data but multiple data, so we pass our results into a list/array.
After we're done writing all our query functions, then we export our schema file, so we can use it in our app.js file.
So include this code inside your schema.js file:
module.exports = new GraphQLSchema({
query: RootQuery,
});
Now we can test our queries by going to our terminal and running the command:
node app.js
You should see Started server on port 4000
in your terminal
Now open your browser and navigate to localhost:4000/graphql
if you remember, that's the endpoint we created for our GraphQL API.
On your browser, you should see something like this:
This is graphiql, the tool we will be using to test our endpoints:
So let's get the details of all the launches that have been made at SpaceX:
Copy the id of any data, then we use it to make the second query to get details of an individual launch.
So we've successfully made our query requests and have got our desired outcome.
Conclusion
From this tutorial we made API request to external API, we can also use GraphQL to fetch data from a JSON file in our project and also more advanced functionalities.
If you like to know more about GraphQL use the comment section to tell me what you'll like me to write on next, you can also check out my previous articles, you'll like them.
Thank you till next time.
Top comments (0)