This post was originally published at https://www.blog.duomly.com/how-to-build-graphql-api-tutorial-express-js-course-lesson-1/
In the first lesson of the Express.JS course, we’ll focus on building a GraphQL API tutorial with typescript.
Express.js is one of Node.JS’s most popular frameworks, which helps us create a backend for our application with the usage of Javascript or Typescript.
It’s convenient because we can do full-stack development with only knowledge of the Javascript.
Don’t worry if you don’t know Javascript yet, we created a course that will help you learn that excellent programming language.
Url for Javascript course for beginners you can find here:
https://www.duomly.com/course/javascript-course/
We’ll create a personal finance app that transforms financial data from the JSON file, and serves that through the GraphQL API.
All of that perfectly works with the React.js front-end that my teammate Anna will upload on the Duomly’s youtube channel.
If you do not know React yet, you can find the complete interactive course here:
https://www.duomly.com/course/react-js-course/
Are you ready for that exciting journey?
Let’s start!
And if you prefer video, here is the youtube version:
As the first step in the Express.js course, we need to create a directory for the project.
Open your terminal and type:
mkdir express-js-duomly
Next, go into the folder by:
cd express-js-duomly
Inside our project’s directory, we should initialize the NPM package, which will let us handle npm packages.
To do that, you need to open a terminal in your project’s directory, and type:
npm init
Next, you’ll need to fill some inputs, or you can leave them blank.
It’s up to you to confirm all the info and the end of the questions, even if they’re blank.
Now, we need to install a few dependencies that we’ll use in the project.
The first is “typescript”, to install that dep, you need to open terminal and type:
npm i -S typescript
The second npm package that we need is “ts-node”.
Open terminal, and type:
npm i -S ts-node
Now, we should install “express”.
Open terminal, and type:
npm i -S express
In this step, we’ll install GraphQL, which we’ll use as the base for our API.
Open terminal, and type:
npm i -S graphql
The last dependency that we should install is “graphql-express”.
Open terminal, and type:
npm i -S graphql-express
Great! All dependencies are installed, so we can go into the coding.
First, we should focus on creating server.ts file that we’ll use to handle the main of the logic of our express.js app.
In the root directory of the project, you should create a file named “server.ts”.
Inside the “server.ts” file, we should import a few dependencies.
The first one is “express”, and the second one is “graphqlHTTP”.
import * as express from 'express';
import {graphqlHTTP} from 'express-graphql';
The next step that we should go into is the schema.
Schema is a kinda pattern that tells us GraphQL what type of queries or mutations we can proceed.
We’ll create a schema for query expenses that will return an array of type “Expense”.
And the second thing that we should do is to create type “Expense” in our schema.
That’ll declare what type of data should the item “Expense” contain.
var { buildSchema } = require('graphql');
const schema = buildSchema(`
type Query {
expenses: [Expense]
},
type Expense {
id: Int,
date: String,
amount: Int,
type: String,
category: String
}
`);
export default schema;
Now we can go into data.
As the first step, we should create a directory named “data”, and a file “expenses.json” inside that directory.
To generate data, I’ve used mockaroo, and have 1000 items, but you can create own, or just clone our repo, and copy the file.
File with data should contain an array with 1000 objects, that have a structure like an example below:
{"id":2,"date":"1/12/2020","amount"1567,"type":"incoming","category":"passive"}
Resolvers are I would say kinda similar to the endpoints in the REST API.
They define what logic should be fired on the typed query.
To create resolvers, as the first step, we need to create the file named “resolvers.ts” in the “graphql” directory.
As the second step, we should import data, return that in the function “getExpenses”, and set up “getExpenses” as a return of the “expenses” method in the object named “resolvers”.
Next, we need to default export object “resolvers”.
You can take a look at the example below:
const expenses = require('../data/expenses');
const getExpenses = () => {
return expenses;
}
const resolvers = {
expenses: () => {
return getExpenses();
},
};
export default resolvers;
To handle all of the node.js logic in the typescript, we need to install types.
To do that we need to open terminal and type:
npm i @types/node
Great, now, we can move into the server.ts, and go into the logic related to the “app”.
As the first action, that we should take is to call express, and assign that to the variable named "app.
Next, we should create endpoint “/graphql”, and call “graphqlHTTP” function.
Below the endpoint, we should set up listening for the port 4000 and return any console.log that’ll inform us when the server is ready.
var app = express();
app.use('/graphql', graphqlHTTP({
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
Okay, we are almost done and have only three small steps to the testing.
Now, we should import schema and resolvers into the server.ts.
import schema from './graphql/schema';
import resolvers from './graphql/resolvers';
If our schema is imported, we can go into applying that, as the “graphqlHTPP” function params.
To do that, we should assign “schema”, as “schema”, and “resolvers” to the “rootValue” param.
The one more param that we should add into the “graphqlHTTP” function is the “graphiql”, and value should be “true”.
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: resolvers,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
Woohoo! Our app is ready.
We can start the API in the two ways, the first one is to open the terminal and type:
ts-node server.js
Or, we can set up the package.json scripts.
To do that, you need to add “ts-node server.js” as the “start” script in the “scripts” object.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "ts-node server.ts"
},
We are done, the app is ready, and we can start testing it, congratulations!
Open the terminal and type:
npm start
Next, go into the URL: localhost:4000 and type the GraphQL query:
{
expenses {
id,
date,
amount,
type,
category
}
}
Congratulations, you learned how to create GraphQL API in the Express.js!
It was the first lesson, but not the last one.
In the next episode, we’ll focus on the Web Sockets combined with the GraphQL that’ll let us create the real-time updated app.
Here you can find the GitHub repository that contains code to the current lesson:
https://github.com/Duomly/express-js-with-graphql-and-websockets/tree/Express-js-course-Lesson-1
Don’t forget to visit our youtube channel, watch React.js course create by Anna, and build front-end to have a complete app.
Here is URL of our youtube channel:
https://www.youtube.com/c/duomly
Thanks for learning with us,
Radek from Duomly
#javascript #api #node #web-development #json #graphql