RESTful APIs in 100 Seconds // Build an API from Scratch with Node.js Express

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
an application programming interface or api is a way for two computers to talk to each other using an api is just like using a website in your browser but instead of clicking buttons and filling out forms you write code to explicitly request data from a server for example we could visit the nasa website to look at asteroids or we could use their rest api to request the raw json data that is shown on the screen now most apis in the world are restful which means they follow a set of rules or constraints known as representational state transfer which has been the de facto standard for api development since the early 2000s a restful api organizes data entities or resources into a bunch of unique urls well technically not urls but uris or uniform resource identifiers that differentiate different types of data resources on a server a client can get data about a resource by making a request to that endpoint over http the request message has a very specific format most importantly the start line contains the uri that you wish to access which is preceded by an http verb or request method which signal your intent with the resource a get request means you just want to read the data while post means you want to create a new resource patch is for updates delete is for removing data along with a few other methods beyond those below the start line we have headers which contain metadata about the request the accept header can tell the server you want the data in a specific format or the authorization header can be used to tell the server that you're actually allowed to make that request then following the headers we have the body which contains a custom payload of data the server will receive the request message then execute some code usually to read from a database that can then be formatted into a response message the top of the message contains a status code to tell the client what happened to their request codes at the 200 level mean that things went well at the 400 level it means something was wrong with your request and at the 500 level it means that the server failed after the status code we then have the response headers which contain information about the server that's followed by the response body which contains the data payload and is usually formatted in json when talking about apis now an important part of this architecture is that it's stateless which means that the two parties don't need to store any information about each other and every request response cycle is independent from all other communication and this leads to well-behaved web applications that are predictable and reliable this has been restful apis in 100 seconds if you enjoyed it leave a comment below then next week i'll pick out the best one to win this free t-shirt and now it's time to go beyond 100 seconds to build a restful api from scratch the most popular framework for building restful apis in node is express.js it's been around forever and it's very minimal and easy to learn if you know a little bit of javascript over the next few minutes we'll use express to build our own restful api from scratch you'll learn how to create different endpoints for your api we'll also look at slightly more advanced concepts like middleware and tools in the cloud for deploying your api like api gateways to get started you'll want to open up vs code to an empty directory you'll need to have node.js installed and i'm using version 12 for this video to start a new node project let's run npm init y from the command line this will create a package json and give us a context for installing packages that we can use in node like express let's go ahead and install express using npm install you'll notice that adds express to our dependencies in the package.json file from there we'll need a file to write our code in so let's create an index.js file at the top of that file we'll declare a variable for app which represents the actual api that we're building and its value is an import of the express package which itself is a function so we'll add parentheses after it to initialize it now at this point our api hasn't defined any endpoints but let's go ahead and run it anyway the way you fire up your api on the server is by calling app.listen that tells it to listen on a specific port which we've defined as its own separate variable as 8080. then as an optional second argument to listen we can fire a callback to let us know when the api is ready and we'll just have it console log the main url we can now run the api by going to the terminal and running node period to run that index.js file and it should console.log it's live on localhost 8080. if we paste the url into the browser you can see we get a message of cannot get that's because we don't have any api endpoints set up yet but express is still responding with an error message in fact you can open up the network tab in chrome if we look closely we can see that our server responded with a 404 status code meaning that page was not found at this point we know our api is working but debugging it in the browser is usually not the best option there are many different ways we can access our api we could use curl from the command line we could install a vs code extension or we could use a rest client like insomnia or postman i'm going to be using insomnia throughout the rest of this video because it provides a really nice way to format your requests and also view a history of all your interactions from insomnia we can create a new request then simply paste in our url we can easily change the http verb from the drop down menu here click send and then get the response in a nicely formatted developer friendly way we can even see the timeline here with our request in yellow and the response in green but now we need to get back to our javascript and add an endpoint to the api we can do that by changing an http verb to the app instance if you type a period after app you'll get intellisense on a bunch of different methods that live on this object and you'll notice methods for git post patch etc which represent different http verbs if we want to add a get endpoint to the t-shirt uri we can do that by passing t-shirt as its first argument that'll automatically set up our server with that endpoint then it's our job to handle a request to it which we do by passing a callback function as the second argument whenever a client or end user requests that url it will fire this callback function to handle the request the function itself provides access to two different objects the request object and the response object the request is the incoming data while the response is the data we want to send back to the client the most important thing it does is allow us to send a response back to the client that response can have a status code like 200 for an ok response then we can send a data payload along with it if we pass a javascript object as the argument then it will send that data back as json by default let's go ahead and save the file then restart the server from the terminal from insomnia we can then make a get request to localhost 8080 t-shirt when we do that we get a json object back as the response body with a status code of 200. that's pretty cool but now let's go back to our code and add a second endpoint this time a post endpoint followed by a slash and a dynamic url parameter that represents the id of that t-shirt there might be millions of different t-shirts on this api and a dynamic url allows us to handle all of them from a single function when dealing with a post request it means that the user is trying to create new data on the server or create a new t-shirt in this case first we need the id which we can get from the url and its value is made available to us on the request parameters object second we also need a logo for the t-shirt but the logo is contained in the request body which if you remember from earlier is a custom data payload contained in the incoming request in other words the request object in express allows us to access information from the request message like the url parameters the body the headers etc and now that we have that information we could use it to save a new record to the database or something along those lines that's beyond the scope of this video what we'll do for right now is check to make sure that we have a logo in the request body and if we don't then we'll send an error response with a 418 status code and an error message that we need a logo but assuming we do have a valid logo we can just send a response with a t-shirt that contains that logo and id now let's go back to insomnia and we'll make a post request to that t-shirt endpoint followed by a unique id that can be whatever you want then in the body section we'll go ahead and add a request body with a format of json and it's just a json object that contains a logo with a string value if we send that request you'll notice we get a 500 error response which means our api code is broken so what's going on here it's telling us we have a runtime error because we can't destructure the property logo from the request body the reason for that is that express does not parse json in the body by default not everybody uses express to build a json api so that's not the default behavior what we need to do here is set up middleware that tells express to parse json before the actual data hits the function that we're using here to handle the request when you hear the term middleware think of shared code that runs before every endpoint callback that you've defined very common middleware is built into express itself we can refactor our code here a little bit to make a variable for express and then we can call app.use to apply middleware in this case the middleware we want to apply is the express.json middleware now every request that comes in will first go through this express json middleware which will convert the body to json therefore making it available in our post callback let's go ahead and save restart our server and then go back to insomnia and if we send the same exact request you'll notice this time we get back a successful response in addition if we make the logo an empty string and try to send the same request we get a 418 response along with a message that we need a logo congratulations you just built a restful api from scratch with node.js and express but before we wrap up the video there's one more thing you should definitely know about when it comes to restful apis and that is the open api spec which provides a standard way to describe an api in yaml it originally came about in something called the swagger framework and what it allows you to do is describe your api in a way that can be understood by both humans and machines and if you're building a serious api you get all kinds of awesome benefits in the process your api will be fully documented making it much easier for the end user to work with and because it follows a standard format you can actually just automatically generate all of your client-side or server-side code what i'm using right now is a free tool called swaggerhub and i can come up here and hit the export button to automatically generate a bunch of boilerplate code now i'm usually not a huge fan of code generators but there's a more powerful reason to use open api when you describe your api with the open api spec you can then upload the configuration to tools like api gateway on aws or google cloud where it can be secured monitored and connected to backend infrastructure let me know if you want to see a full tutorial on that topic but i'm going to go ahead and wrap things up there and if you want access to even more advanced content consider becoming a pro member at fireship io thanks for watching and i will see you in the next one
Info
Channel: Fireship
Views: 269,161
Rating: 4.9812584 out of 5
Keywords: webdev, app development, lesson, tutorial, http, rest, rest api, restful api, what is an api, node.js, js, express.js
Id: -MTSQjw5DrM
Channel Id: undefined
Length: 11min 19sec (679 seconds)
Published: Fri Feb 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.