Planning & First Steps | Creating a REST API with Node.js
Video Title: Planning & First Steps | Creating a REST API with Node.js
Welcome back to this series where we built a restful api with node.js in the last video we had a look at all the theory and that was important but now let’s dive into the fun stuff and let’s start building a restful api so let’s have a look at what we’ll build
And then let’s start with it so what are we going to build in this series our api will have a couple of resources i want to build the api that’s realistic and that contains some things which are typical to restful apis for this we’ll have a products resource so slash
Products is one route we can target and there i want to support get requests to get a list of all the products we have post requests to add new products i also want to be able to target the individual product by id and get information about that product
Patch that product so change it update it delete this product so that we can get rid of it and let’s also implement our orders resource where we can place orders so where we for example could get a list of all the orders we have i also want to be able to
Post a new order so create a new order and i also want to be able to then access my individual order and just like for products get more information about it and not patch it let’s say we shouldn’t be able to edit our orders but we could delete so cancel them
That is what i want to build we’ll also add authentication to make sure that some of these routes of these endpoints are protected so that only logged in users can access them and therefore you will also learn how to log users and when building a restful api because we can’t use
Sessions remember from the last videos so that won’t work that is what we’re going to build we’re going to build it step by step we’re going to start with it right now so let’s start with building this restful api and for that i’ll navigate or i navigate it already
In the folder where i want to create this project make sure you do the same and then in the terminal here i’ll just run make here for make directory to create a new directory and then the name of the project and you can of course also do this in the windows explorer or
The finder manually you don’t need to do that in the terminal i’ll name it node rest shop something like that then with cd node rest shop i can navigate into it and now we have an empty folder now we first of all need to put this under control of npm nodes package manager
Because i will install a couple of dependencies and i will install them all through npm this dependency manager tool for that you need node.js and you will need this anyways since we’re going to create a node restful api so having node makes a lot of sense you can get node.js from nodejs.org
Either download the latest version or if you’re facing any issues with that download the long term stability version 8.9.1 at the point of time i’m recording this once you got this simply type npm init in this new project folder and this will now walk us through a
Little wizard here which allows us to initialize that so you can assign a package name version some description like a node.js restful api tutorial project build a simple shop api something like that entry point doesn’t really matter for us here test command i’ll leave that empty
You can enter a git repository i won’t do that for now can enter some keywords don’t need to you don’t need to and an offer here i’ll put my name finally you can choose a license i’ll confirm this default license and type yes with that we got this new file in there
And i will now open this whole project in an editor now i will use visual studio code but you can also use a another editor sublime web store adam whatever you like so i opened the project we just created in this editor and there you see this package.json file
That was created automatically through this npm init command and here you can always tweak these things you just confirmed in the terminal if you want to now open the terminal in this editor that’s the built-in uh terminal into visual studio code it’s the same as the default terminal on the operating system though
And i now want to install a couple of dependencies we’ll need we need node.js but we already got this on our system so what i will install here with npm install dash dash save save creates an entry in the package.json file is express because i will use express
As a framework for nodejs to make building this api a bit easier and we’ll add more packages throughout this video series but let’s start with this one with express installed i’ll add a new file to the project by clicking on this icon here or simply hitting command n
And i’ll name this file server.js here i will set up all the code to spin up my node.js server which as you probably know we do through code through javascript code so not like in php where we have a separate server software which then kind of is connected to our
Php script and stuff like that we create a server instead in javascript when using node.js now how do we create that server then we’ll first of all import something from node.js and i’ll store it in a constant name http const and let our next-gen javascript features which node.js in
The later versions supports and i do import it with require http now if you worked a lot with single page applications or with front-end javascript development in general you might be used to the import something from something syntax now this syntax is not yet supported in node.js
Hence this old or still the only import syntax we have in node.js so this http package i’m importing here provides us some functionality we need for spinning up a server additionally i’ll create a new constant port where i will assign a port at which my project should run
And here i want to either get that port through an environment variable or i will hard code it in there now the environment variable would be process.nth.port and process.n simply accesses nodejs environment variables and this would be set for example on the server you deploy it on most hosting providers offer you
The id opportunity or offer you tools to inject environment variables into your running project and then you would simply add this port environment variable if it’s not set however we’ll use 3000 as a default port thereafter i’ll create my server and store it in a constant with this http package and then the
Create server command now to recreate server we need to pass a listener so a function which essentially is executed whenever we got a new request and which then in turn is responsible for returning the response i’ll leave this empty for now but we’ll add something soon with the setup we have here it
Wouldn’t really work because we need to handle incoming requests thereafter i’ll call server listen to really start the server and i’ll pass the port as an argument so it starts listening on this port and then it will execute whichever listener or function we passed to create server that’s the idea
Now this is a very simple server setup i’ll now add a second file app.js and this file now is spinning up this express application which will make handling requests a bit easier for us so how does this now work there i will create a new constant named express
And i will require express that’s the package we just installed with npm install dash dash save i then will create a new constant app and just execute express like a function this will spin up a express application where we can use all kinds of utility
Methods and so on now i will add more and more functionality to this file for now what i will do is i will simply add app and then call a method on app and that method will just be use now use as a method sets up a so-called middleware
So an incoming request has to go through app use and to whatever we pass to it now the thing we pass to it can have different formats it can simply be a function like an arrow function you can also use a normal one where you get the request the response and some special
Next function the third argument here is actually a function which you can execute to move the request to the next middleware in line and if you don’t execute it the request will not go there and here what you could do is you could simply use response to send a response
So you can here simply send a response and let’s already send a json response by first of all setting a status code it’s a method and takes the status code let’s send 200 for everything okay and then the json method and this will send a json response
So with the right headers set up and so on and there you can pass a javascript object will automatically be stringified for you because json data which is sent over the wire is in string format and there we could add a message property whatever you want and simply say it works
Now with that set up what we have to do at the end of the file is we add module exports and set the sql to app with that let’s save this file and go back to the server.js file and there i will now import app with require
And then i’ll point to slash app this app file we just set up you can omit the file extension here by the way it will automatically look for js files now i pass app to create server and the express application qualifies as a request handler so with that we
Have a setup that should actually work and allow us to send a request a get request right now or any type of request actually to this back end and this middleware should make sure that we actually receive a response let’s try it out and in the terminal
In your project folder where you ran npm install you can now run node to start something with the node library and target server.js and this will execute it with node.js and keep this process running it doesn’t finish so it’s not stuck it should keep on running because you just started your server
And now how can we see if it works well for now since we started this on our machine it runs on localhost and then at port 3000 because we don’t have environment variables here so it takes three thousand let’s try it out in the browser there if you enter localhost 3000
You should see a message it works and by the way you should also see this if you send some different kind of request like a post request now we can’t easily simulate a post request for the browser like this but we can use a useful tool for this the tool
I mean is called postman you can simply google for it and you should find getpostman.com it’s a tool which helps you with developing apis it allows you to simulate all kinds of different requests you can download it for the different operating systems so i’m going to go with
Mac os here and then simply follow the instructions here install it enter the api endpoint and so on once you started it you’re prompted to sign in but you can skip this and now you can create a new request so if you click here you can give this a name
And a description you can all just exit here and now you’re on this screen on this screen you can always create new requests by clicking this plus button here but then you can choose the different http words now we won’t support all of them in this restful api and
Some of them are really rarely used but we’ll have a look at get post patch and so on so let’s try a post request and let’s send it to localhost 3000 just like this click send and you should also see message it works and here you can also choose between the raw format
So the request body as it looked like a formatted one and preview here also is nice if you for example would get back html that tries to preview it in a nicer way you can also have a look at the headers which were created by default like
Application json that was set up because we used this json method here on our backend and with that we created our first very basic restful api now it’s not really useful it doesn’t have different endpoints it’s not adhering to all the constraints we set up but the base functionality here isn’t
That wrong now let’s continue on this road and let’s have a look how we can improve this and get closer to the api setup we sketched out earlier in this video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Did i did anything wrong?
I coded it just like you, but im not getting the right response. Neither with my browser, or with postman.
This is the Code in the server.js file:
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 4000;
const server = http.createServer();
server.listen(port);
And this is the Code in the app.js file:
const express = require('express');
const app = express();
app.use((req, res, next)=> {
res.status(200).json({
message: 'It works!'
});
});
module.exports = app;
The Node.js version is 20.9.0
And VSC ist triying to bring me into the "import smth from smth" algorithm by putting 3 dots under my require keywords.
I want to make a little application , for me, basically a CRUD, but simple ! It's not possible with json-server , there are prolems with CORS that I 'm not able to solve. I would have done withouth a db , but I think this is the only solution: mongo, express, I hope I can solve the CORS problem with it, and to understand better FRONTEND and BACKEND. I'll follow all the lessons , I want to change my app json-server , crud, differents pages html, js
await fetch('http://localhost:4000/posts', {
method: 'POST',
body: JSON.stringify(doc),
headers: { 'Content-Type': 'application/json' }
})
we want it again in 2023
Hi Maximilian, thank you for all the knowledge you have being pouring out. This is the second programming language I will be learning with your materials. The first one was from Udemy and I really enjoyed it.
Talking of PHP, I'll like to ask if you have a PHP course for building Restful APIs. If yes, please share the link as I've looked around for it and can't find it. If no, do you have plans of making one soon?
Hi Maximilian, thank you for the informative video on creating a REST API with Node.js. I found your explanations and step-by-step process really helpful.
I noticed that you used pure JavaScript for your backend application. I was wondering what your thoughts were on using TypeScript instead. TypeScript has some great benefits like static typing and improved code maintainability. Was there a specific reason why you chose not to use TypeScript in this particular project?
I'd love to hear your perspective on this. Thanks again for sharing your knowledge through these videos!
Is this course outdated ? Please I am starting Node.js and let me know
can someone provide me with source code. Please
throw err;
at node:internal/main/run_main_module:23:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
Can't show message at localhost instead give error 404 not found!
You are awesome!!
thank you SO MUCH!!
it's exactly what I have to do for my final school project but my teacher doesn't explain anything and instead, gives us the website of Node.js for the documentation! -_-
You're a real life saver!!! 🙂
No one is getting an infinte loop on localhost?
When creating the "app.use" what does the => represent?
Thanks learn a lot from your vedio 😎 amazing bro
why am i getting site cant be reached when i search localhost:3000
thank you
A perfect teacher to learn any CS technology! Keep it up Man!
I have a doubt….should I watch this video now after 4 years without the fear that some things might be outdated as compared to 4 years ago??? :/
This video is the most apt to my project even after 4 years of its release. Just want to say thank you, to Academind!
Why does he use both express and http? Express is enough to get the job done in this video….. I am confused….
good information 🙂
thank you
Academind
for this part
Bro you are great did well.. very good explanation…. love you brother. 🙂
Max has been teaching me to be a better developer for three years now! Let's goooo! 😊😊😊😊😊
I got this : TypeError: Cannot read property 'method' of undefined
at Function.handle (D:NodeJs Projectsserver_tutorialnode_modulesexpresslibrouterindex.js:139:34)
at Function.handle (D:NodeJs Projectsserver_tutorialnode_modulesexpresslibapplication.js:174:10)
at app (D:NodeJs Projectsserver_tutorialnode_modulesexpresslibexpress.js:39:9)
at Object.<anonymous> (D:NodeJs Projectsserver_tutorialapp.js:12:18)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
PS: I Wrote And followed you tutorial exact… What's going on Max ?
I loved how you didnt care too much for the slide layout as long as it passed the correct message. What happened to these slides? All aligned… sigh. Not my style
For some reason when I try to reach localhost3000 it just keeps loading and loading. I don't understand why it doesnt display "it works"
Спасибо за науку! Разговорный английский плохо понимаю, но тут всё интуитивно понятно )
I almost never comment on tutorials, but this was a really good tutorial. It was short and I feel like I actually learned things instead of just copying code. 👍
but if I host node on a goddady server, in need to use node on my laptop to setup the files then use ftp to put them on the server – you cant work on node js as you are on the say goddady server..
mind blowing man, the best tutorial on the youtube platform, beginners and experience both required a explanation like you, hats of you man…. MAX you are a legend. Thanks a lot for this tutorial
For best tutorial on node js watch w3 Grads:
https://youtu.be/wefZImC7vn4
https://youtu.be/iHQXkxiwi3Q
This is helpful, also purchased angular course on Udemy. Love your teaching style.