Learning The PERN Stack — Express.js
Welcome back to the series !
This section is gonna be the most fun and interesting to you because we’re going to learn important concepts in any software which are
- Creating our server
- Hooking our backend to our database
- Testing out our API
So today we’ll be setting up Express.js which is a framework for node.js that helps us quickly create a RESTful API to interact with our database so let’s firstly define some “fancy” nerds gibberish
What’s An API
An application programming interface or an API is a way to allow different programs to talk to each other through HTTP
A real life example is : let’s suppose you’re building an anime web app where anime fans can view upcoming episodes and info about their favorite shows but there’s a problem how the heck are you gonna retrieve such data ?
That’s when an API comes into the picture, an API allows our computer to connect to a remote computer (server) asking it for that info and the server will send the desired info if available and queried properly
What’s HTTP
It’s the protocol that allows us to browse the internet, the internet in its core is a cycle of requests and responses and the way those are organized is HTTP which is a set of rules that dictate this process and there are many HTTP “verbs” or methods we can make but the most common ones are
- GET : to ask for data
- POST : to submit new data like forms for example
- PUT : to update existing data
- DELETE : to delete data
And a RESTful API is an API that provides endpoints that allow those methods and other HTPP methods, that’s why it’s called RESTful
What’s JSON
So just like how humans respond to each other with an understood language, servers too have their own “language” when responding to requests from clients and the most common way of response is JSON which stands for Javascript object notation and it pretty much looks exactly like a javascript object like in this example
{"name":"John",
"age":25,
"isMarried":true}
Now there are other forms of response like XML but JSON is the most prefered and common as it’s easier to parse and extract needed data from
How Can I Make My Own API
So as we’ve just seen what can an API do i’d like to mention that’s not the only thing we need an API for, in our case we need to “talk” to our database through code and not just by pulling up Psql each time a client wants to make some changes so that’s why we need to build our own API to talk to our database and the best way to do that is to use Express.js
In that previous example we successfully created an express server that listens on port 3000 for connections and we added an optional callback just so we’re alerted that everything worked well
Installing Express And Create Some Endpoints
To install express just run the command npm install express
and it’ll install it locally
Now we’re gonna set up few endpoints and explore the features we need now
Endpoints And Methods
Since we’re now aware of what RESTful means we’re gonna create a skeleton server to interact with our database
So lemme explain the callback part of those endpoints, so basically each time we make aN HTTP call to any of those endpoints we need to supply a function (callback function) that is only triggered when such event happens to let the server know what to do and how to process the request
This callback takes two arguments, a request object and a response object RESPECTIVELY and having access to those objects allows us to do many things including but not limited to :
- Responding with a normal message
- Send back a file like an html page when a user clicks on a button
- Send back a JSON response
And many more you can check here, We’re more interested in sending back JSON so let’s do that when a user makes a GET request to the /employees
endpoint
The magic of express will turn our object we passed to JSON
Now let’s talk about middleware as it’ll help me explain to you more concepts regarding the request object
Middleware In Express
Middleware are functions that help us achieve more functionality with our routes, for example express.json()
is a middleware allows us to access data inside the request body and that helps us to process data and save new data to our database and that wouldn’t be possible without using that middleware
So let’s see how to add that to our script
app.use(express.json());
and BOOM just like that we can now access the request body and grab the data we need from it, say the user sent a post request with new employee info so we can now “hook” to that info and add the info to our database
The Request Object
Now that we went over what middleware is, let’s now find out what other things we can do since we enabled express.json()
Now we have access to the request body and parameters, but what do those two even mean
So let’s suppose we made a GET request to http://localhost:5000/employees/1
in this case anything comes after our route is called a parameter and we can of course hook to that and do stuff with it
Remember we had a route /employees/
express will look at the request and match the routes we have with this incoming route and decide the paramters
Checking Our Parameters
So first off let’s install nodemon real quick npm install nodemon
and that’ll run our server and update whenever we make any changes to our server file without us having to manually restart the server
Now pull up your command line / terminal and navigate to where you kept your express.js file and run command nodemon
as it’ll identify the js file on its own and run the file, you should see the message from the callback telling you the server is up and running
And now we’re gonna add some code to our GET routes just to test out and see what comes back to us
Now go to your preferred browser and type in the address bar localhost:3000/employees
then check your command line
Let’s now add some query parameters and modify our server file
Make the same request now but add anything after the / and notice the response
So you can pretty much name this parameter anything you want and now the server will return us this JSON containing a key-value pairs of the parameters we specified on the route and what we supplied
To access specific values within the response there are 3 ways so pick whatever you like
- using dot notation
req.params.userid
- using those square brackets like in an array
req.params[userid]
- destruct syntax
const {userid} = req.params
and it’ll extract the value specified in those curly braces — note this is an ES6 feature
Hooking Our Server To Our Database
This is where the fun starts, we’re gonna now connect our db to the server so that we can now alter our tables through node itself and to achieve that we’re gonna use an amazing node module called Pg
and to install it we use npm as always so we go npm install pg
and what this basically does is it helps us to connect to our postgresql db very easily
Connecting To Our Postgresql Database
Create a new file and name it db.js
and paste in the following
We then exported it so we can require it in our server.js
file where we have our server logic
Creating Our API To Interact With Our Database
Now back to our index.js
or however you named your file and let’s require our pg object and configure our routes
Note we used async/await because it takes time to retrieve data from the database so we told the program to wait until the function resolves to proceed to the next steps and to also be able to use try/catch blocks for error handling
Adding A Route To Return A Specific Employee
As we discussed earlier, passing parameters to the URL is very helpful and those params can be easily extracted so we can pass an id and that’ll be a part of our SQL query just like this
POST Requests
I explained earlier the most common http methods and what we have been doing through our browser is a GET method which is the most common one since we’re always “requesting” to visit websites so it’s easy to implement a GET method but what about the other methods? How are we supposed to test those routes ?
First off lemme give you an example of a POST request, When you login to any website or fill any form in general that’s a POST request, you’re ssending out information to a remote server in hopes of having that processed so the server will react accordingly
In our scenario we will allow users to add new employees through a form we’ll get into when we discuss React in the next chapter, so that we’ll be able to capture that info and see what to do with it
Right now to build and test out our POST and UPDATE and DELETE routes we’ll need to download an amazing software called Postman, Postman allows us to test out our APIs super easily and smoothly and we’ll also look into request body, it’s similar to query parameters but the actual data we send, say form fields in our POST request is called the request body and we can hook to those as well
Installing Postman
Head over to this link to download it, it’s pretty simple and straightforward and then you should see a screen like this
As you can see it’s a very friendly interface where you can select the http method and the URL then hit send, we’ll get into little more details next
Testing Our POST Request
To make a POST request to any endpoint we need to provide some data right ? since we’re sending out data to a server so how do we exactly send data and what should that data be ?
The task is fairly simple using Postman so let’s first see how to do so and then we decide what to send
In the address field just type localhost:3000/employees
On the next screen choose raw then select JSON then create a JSON object down below
Printing Out This Info
Now that we know how to send POST requests to our API, let’s modify our route to return to the user whatever info they sent
As you can see you can access the values within the JSON response the same way you access the query parameters passed in a URL
Let’s take a look at Postman and see the response when we ask to access the first-name
value
Inserting And Retrieving Data From Our Database
Now let’s use pg
to help us add new records to the db and also return us in JSON form all the employees
Quite chunky i know :D but the code is pretty simple now that we went over the basics
- an SQL INSEERT INTO statement to insert data into our employees table
- those dollar signs are just place holdersbecause it’s preferred to pass the value in an array as a second argument to prevent SQL injection
- SELECT statement followed by a * to return all the records without any conditional
- using the WHERE clause based on the id passed in the URL
Now you can practice more with Postman and send different POST requests and the row
property returns you all the data in your database so you don’t have to switch back from your editor to Psql
One more note, the ‘keys’ you send in your POST request — the JSON body we constructed in Postman- have to match those values we extracted using this destructuring syntax so for example if we sent such POST request
In this case the server is expecting a property named “name” but instead received “names” so this wont be assigned to a variable since the expected property doesn’t even exist
PATCH And DELETE methods
Implementing a PATCH method is quite similar but let’s remember how to update an SQL table
UPDATE employees SET fullname="Courtney" WHERE userid=3;
so we’re in need of two values to be captured, a new value to update the old one and a conditional so how do we go about that in Postman? Example down below
And this way you can set up routes to update other values and not just the fullname
column but i was just making an example
Let’s head over to Postman and make our PATCH request
Then you can make a GET request to /employees/
to check your new data
DELETE Method
And just to implement that using Postman we do the following
Now let’s see the GET method output and if we still have an entry with userid = 3
Putting It All Together
Now that we’ve reached the end of this article, let’s put all the pieces together
And our database file here
Big thank you
I really appreciate it if anyone made it this far and i hope you learned a thing or two and i’ll continue with the series