Node, SQL, & PostgreSQL - Backend Web Development [1/2] | David Katz | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Node, SQL, & PostgreSQL - Backend Web Development [1/2]

teacher avatar David Katz, Software Engineer - Coding Instructor

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

20 Lessons (2h 10m)
    • 1. What to Expect from the Course

    • 2. Optional: installing Node

    • 3. Optional: Installing a Code Editor

    • 4. What is Node.js?

    • 5. NPM, Modules, and a Node Program

    • 6. First HTTP Server

    • 7. Optional: HTTP and Web Requests

    • 8. ES6 in Node

    • 9. JSON, Nodemon, and more Advanced Functionality

    • 10. Optional: the Event Loop

    • 11. Express

    • 12. Setting Up the Fortunes API

    • 13. JSON for Fortunes

    • 14. First Express Endpoint

    • 15. Optional: Startup with an Executable

    • 16. Get a Random Fortune or One by ID

    • 17. Fortunes Post Method

    • 18. Clean the Fortunes Post Method and Use Postman

    • 19. Update Fortunes Put Method

    • 20. Delete Fortunes Method

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

Become an in demand software engineer by taking this course on Node, SQL, PostgreSQL, and backend web development. As one of the most popular web development stacks today, learning Node, SQL, and PostgreSQL is a must. Knowing these languages and frameworks will open doors and jobs for you.

In this project-based course, you’ll learn how to build Node, SQL, and PostgreSQL applications by building three full projects. You’ll discover some techniques widely used in the industry today. And you’ll find out how to use notable libraries like Express and Pg.

You will skyrocket to the top of the talent pool because you can build backend web applications. The backend is the heart of services and products. So knowing how to write the backend is the other highly crucial skill looked for by top software companies like Google, Facebook, Microsoft, and more.

In this course, you’ll get familiar with Node by building an application from the start. First, you’ll learn how to use the native Node modules to build a server.

Second, you’ll build a more in-depth application with Node and Express to learn how to a build an api with a complete set of http request methods.

Next, you’ll dive into SQL and PostgreSQL to build a solid foundation around these tools. After, you’ll build an api that combines all the previous concepts with Node and PostgreSQL so that you understand how to create Node apps that work with advanced databases.

If you’ve already gone through the the quick JavaScript and web development tutorials online, then this course will take you to the next level.

Ready to step up your coding game? Excited to boost your skills? Then what you are waiting for? Let’s get started coding!

Meet Your Teacher

Teacher Profile Image

David Katz

Software Engineer - Coding Instructor


David is a software engineer at Zendesk, with a Bachelor of Computer Science from the University of San Francisco.

David has gained valuable experience from the tech industry. By incorporating these best practices, he hopes to create the highest quality learning experiences possible.

Feel free to connect with David! He is always curious about the cool project you're working on. And he loves to discuss ideas on how to build impactful technology.

See full profile

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. What to Expect from the Course: I'd like to officially welcome you to this course node SQL postcard SQL Mastering Back End Web development. Great thinking on taking the dive into back in Web development. It's one of the most sought after skills since companies rely on the back end for the core of their services and products. What can you expect from this course? Well, this course has one goal in mind to get you to confidently add node.js, SQL and postcard SQL as skills to your resume and new items within your coding skill set. If you've already learned a little bit of either node or post rescue l or both, then consider this course a nice refresher for the concepts. This course is a project oriented tutorial, so topics will be introduced on a high level by explaining what key terms mean and what main topics cover as we build projects and go along once we get an understanding of concepts, will solidify that again by building our projects together all together, we'll build three full projects. First, will make a back end server with node to understand the essentials and build a foundation. Second will step up our game by mixing and Express to build a full A P I. Next we'll explore SQL and Post Rescue Well, to build another foundation on these back end database tools. And third and finally for our projects will build a full back and server in a p I with note and post press bringing all the concepts together. That way, we'll learn how to effectively manage and serve up data for Web applications. All right with that, let's get ready to learn node SQL and post Braschi well and get started coating. 2. Optional: installing Node: Let's insult No, Jess, go to a new tab in your browser and search No Gs, one of the first links that should pop up. It's a no duchy s dot or glink. Go ahead and click on it and then we'll find the home page of node dot Js in home Donald, the most current version of node 8.8 point one the newest one. Now, if you don't use a mac system, head to the downloads tab over here and find a link relevant to your operating system and platform. Whether you need the windows and solar, the limits installer note has it for you. So once you have the package, go ahead and open it. Once you do. So you find a series of steps just like so and this will allow us to install note globally on our system. We're gonna go ahead and continue through these agreements. You can read the documentation. Click agree. It's like your system to install it on your drive and then install. You'll need to enter your password as well to install the software, and soon enough it will be installed and have all of its files written and There we go. It is completed. Installing now to check if it's installed. Go ahead and open up your terminal application. You can use the spotlight feature on Mac by doing command space and then typing in terminal on other systems. You're going to want to find the command line. I believe it's command prompt on Windows. Now, for those of you new to the terminal, you can basically think of it as a type version of finder or the folder. Explore on your system. Except we can also launch programs. From this, we can navigate through folders or directories by typing in CD, which means change directory. We can also type in L s to see what folders are there for us and now on the terminal. We could also check if node was installed correctly. You should be able to type node and in the space and in the dash V option, which will give us our node version. And the version should match the one that we just installed through the download page. Version 8.8 point one. Also type in NP envy and she gets something higher than version five. No, npm is a package manager, the Node package manager, which automatically ships with node whose primary function is to install modules or packages for note. Think of a module as the container of code relevant to a specific node function or programming concept. We use a lot of NPM in this course, so you continue to learn all about it. Great. With no GS and NPM installed, we have the next couple of tools ready for us to code. 3. Optional: Installing a Code Editor: Now it's insult. A code editor with the code editor would be able to modify follows for our projects and develop our applications. Now I find one of the easiest coat editors work with is visual studio code. If you don't use visual studio code as your editor and you already like to work with another one, by all means use that one. There's many solid options out there, and they're all really good. For example, I've you sublime heavily in the past on Also use Adam quite a lot to But recently I've been using visual studio code in finding many their custom options to be quite nice. Okay, to set up visual studio code, you can start by going to a browser and simply searching set up visual studio code or set of ideas code. You'll find a link over here, set up the S code and go and click on it and you'll find a page just like this. Now you find that visual studio code goes on multiple platforms like Mac, Linux and Windows, so go ahead and click the link for your relevant one. If you're on the Mac, then feel free to stay for the rest of the lesson to see an installation. So let's go to the Mac, then here we find a download visual studio code down the link. And there we should see. Yep. V s code Darwin stable dot zip is downloading. Then once it's finished downloading, we can go ahead and open up. Visual studio code are new application. So there it's expanding. Once we double click that zip file, and here we find a new visual studio code editor. Now, what you want to do next is actually drag your visual studio code into your applications folder now already have one. So I'm gonna go ahead and stop this, but for you, it'll just go in automatically if you don't already have visual studio code Now, for the next step, you'll want to open up your new visual studio code editor that one of the nicest features about visual studio code is its command line path feature. Not to find what I'm talking about. Gun, press shift command P all at the same time. And look up Shell Command. Now you want to install the code command in your path. So once it's installed, go ahead and open up your terminal. And the effect of this is that now you have access to this code command in your terminal. Now, the great thing about this command is it allows me to open up any folder that I want within the terminal so I can go into my NPM folder. And then I could easily open everything within here by simply doing code dot and there will open up our whole folder within Visual city code ready for us to explore these different files. Excellent. So that's what that Shell Command does. It allows us to use the code command right within our command line. And it's very simple trick and will help us for development, since it would be creating a lot of projects within our terminal. So certainly using this code command to open up our creative projects will be very useful. Does that cover is getting a coat editor again? You don't have to use visual studio code. It's just really simple to set up, which is why I'm guiding you through this installation. All right, let's move on 4. What is Node.js?: what is no DGS defined by its documentation, Loader GS is an asynchronous of Ben Driven JavaScript runtime designed to build scalable network applications. That statement comes with more than a few loaded terms, so let's impact that bit by bit. Let's start with the fact that is designed to build scalable network applications. Well, what is a network applications? First of all, let's explore what we mean when we say application. An application is a computer program with an interface, such as an interactive display for the user to accomplish tasks like word processing or making spreadsheets. Applications that come to mind are Microsoft Word or a code editor. Like sublime. These applications are stand alone, meaning we edit data locally and store it in the same computer. Now let's distinguish this from the concept of a network application. Network applications use a client server architecture, which, at a bird's eye view, means there could be two or more computers involved in handling data. The client, usually a desktop laptop, were now mobile devices like an iPhone access the services of the Web server. The server, a computer itself, is hosted somewhere else, often within a large data center the much more powerful server computer handles heavy jobs , like managing a large number of files or other processes. Then the client runs applications that were lying on these powerful servers for Resource Is and the processing power. A fitting example for this client server architecture model is a Web browser. Google Chrome runs a Web client program to allow you to access the Internet. And when you make a request to the server with actions like Google, search, their Web servers run programs in a data center to retrieve the information to display to you So in summary Note is designed to build network applications. And a network application is one that uses a client server architecture, where a client computer runs an application that sends and receives data to be processed by a server. Now let's dive into the idea that no DGS is an asynchronous event driven JavaScript runtime . Let's start with defining a runtime. No togs is a runtime, which means that this kind of program executes instructions while the program is running. Even those that we did not write explicitly or know beforehand. Let's think of this in terms of node creating our network application do a program by acting as the server node will start the server program and throughout that servers run time, it may receive instructions from a client to process files or retrieve information from stored locations. These instructions aren't exactly known when the program starts, but they can happen at any time. Finally, what we say Java script runtime. We mean that no Duchy s is a runtime implemented in JavaScript code. This leads us to the idea of node being event driven. In the event driven model, A program follows a flow of events determined by a user again no. Through its run, time performs different actions in the program. Depending on the events submitted by the user, such as requesting for backend, resource is processing some file data sent by the user and more. These events can happen in any order, so the flow of node is driven by these events. Finally, we get to the last part the first adjective notice asynchronous In terms of sheer computer science, an asynchronous program will allow operations to continue simultaneously meaning while in operation is executing. It can start new ones without blocking the old operation. Perhaps it will help to distinguish an asynchronous program from a synchronous one in a synchronous application. On the other hand, the handling of operations is sequential, everything gets streamlined and things occur one after another in a direct order. This makes a programme simpler in terms of a step by step process. But if the application wants to do more than one thing has to block the next operation until the current one finishes, Let's go back to our server example in a synchronous system. Let's say the server is currently processing a huge amount of data that is taking two whole minutes to complete. A new request comes in to grab information and retrieve a small file with just a couple lines of information in it. This process takes two seconds, but the two second data retrieval needs to wait until the whole two minute data processing completes in order to occur in an asynchronous application. This data, which evil can happen while that other data is being processed? This gives the client server much more power as it can put heavy operations in the background and still provide the client with a fast and reliable service. All right with the idea of an asynchronous application down we've now fully impact are starting definition of no Dutch. Yes, in summary, NOTTs is an asynchronous application able to handle more than one operation in a non sequential manner. Node.js is event driven, defined by an unknown Siris of user submitted events. No DGS is a job script runtime implemented in GS that can handle different events throughout the lifetime of its program. And finally, NOTTs is designed to build network applications in the client server architecture excellent . 5. NPM, Modules, and a Node Program: with our solid understanding of node, let's jump right in and create our first node program to start head to your command line, application and neck. You compress command space for the spotlight feature. Just like so, type in terminal and their press enter. You'll launch the terminal application as it appears just like so on Windows. The application for the command line is usually called command prompt with the terminal open. Now, let's make sure we have note type in node and then space Dash V. For the version number, you should get a version around eight or higher, which is the most current one at this time. If you also have Version six, that's fine. That version is the more stable industry standard and should support all of the features we use in this course. If you don't have note installed, be sure to head to the beginning of the course recon. Find a tutorial on installing it with node. We should also automatically get NPM, so if you type in NPM be, you'll find your version of NPM, and you should find something higher than version five or version three. If you're also using note. V six you might be wondering what NPM does and accomplish and what it stands for, and PM or the note. Package Manager is a tool automatically ship with node that allows us to initialize note projects and install relevant modules for our projects while developing applications. The subject of modules will continue to appear as these modules or JavaScript libraries will allow us to create powerful features for our servers and note applications. For our first step, let's make a new folder for our first no project. You'll probably want to create a folder for this course to How about node post GREss? To make a folder, use the M. Kader Command, which stands for make directory. So it's M. Kate Dirt de ir, and then note underscore post dress for the folder of this course. If you type LS we should find that node. Post Press is now available in our folders. Then let's navigate into that folder or directory by using the Change Directory Command CD for short and then once I type it node, notice that this is the only thing that has node as its prefix. So if I press tab, it automatically go up to new Post Press. Then I can type enter to complete the commit. Great Never. We have a folder for our node post grace projects. Let's make our first project one called First Server Again. We'll use the Make Directory Command so it's M. Kidder and then create our project, which is first underscore server. Now let's change the directory into that one. So if I type in first night press tab, it'll auto complete. And there we are in first server. Nice. Now we'll initialize our project using NPM and PM comes with any command called in it, which allows us to create the note. Project Interactive Lee. So typing in PM Let's run the command in PM In it. What follows is a series of questions about the note project, like the name of the project, the description, the author, the license, etcetera. We can click enter for all these questions to go quickly and customize them later if we need to. So once it's all done, we're gonna say yes. This all looks good. An offi type in ls weaken. List the directory contents of first server and we find a package dot Jason file was created. This package dot Jason contains the information we just confirmed. So in order to see that on the command line, we can use the cat program. So it's cat package got Jason, and this prints out the file contents on our command line. And here we see that we have Oliver answers to those questions we quickly answered in the interactive NPM innit feature. So it's all contained in this Jason, Va. We'll dive into Jason later, but if you're unfamiliar with the file type, you can think of Jason as a file full of JavaScript object data. All the keys are surrounded by quotation. Marks for our note project are packaged out. Jason Fall represents our configurations and lets out ways We can also interact with the project. Great. We've now set up our first note project. Let's move on and start adding the code to turn it into a server 6. First HTTP Server: Let's are building this server. We'll start by opening up our project in her code editor. Use whatever editor you're most comfortable with. If you installed visual studio code at the beginning of this course, you will probably have the command line shortcut. So type in code in space dot in the command line to open up our first server project. So here it is going to go ahead and make this full screen. Now, if you're wondering what that full screen feature was, I have this tool called size Up installed on my Mac, which allows me to easily move things around. For example, I could put things in corners on left, top bottom or right, and make things full screen very quickly. Now it's a paid application, but a little investment towards improving your developer life is usually worth it. So consider going to size up and using it. Here we have our project with its package Dajae Santa. Now, if he opened up the package Dajae Sandra, you find the main field points to an index dodgy. As far this essentially means that the root of our project will be a JavaScript file called index dot gs. Well, we don't have that file at the moment, so let's create it going to go ahead and use visual studio code to create an index dodgy as far. And there we have our index dot Js file for our very first step. Let's write some code that will allow us to treat a Web server will require a module called http to do this. Now there's two concepts to unpack in that statement. First, we have the idea of modules. Modules in note represent packages of code that allow us to add certain features to our JavaScript note applications. In the case of http, http is a core module to note so we don't have to install it separately. We can use it right away, since it's included in no duchesses source code. So we'll grab our http module in store it in a constant object called a teepee or rather, H to tp. And then we'll require http module just like so. So we point to the module with a string, and then we use the global require function that no duchy s provides for us before we move on. Let's clarify http. Http says for hypertext transfer protocol, and it's a standard for transferring data and communicating across the Web. It essentially allows us to transfer data through hyperlinks across Web pages full of text . In our case, we're making a server in this http protocol format current. Now that we have the H T T P module, let's cover the next two steps defining our host name and report for the Web server. In that working, the host name is a label assigned to the server to identify it to other applications on the Web. For example, domain names like Facebook and Google are officially established host names in the domain name system of the Internet. For our purposes in development, we can attach to the local host host name, which is a host name that hooks up to the local computer. So create a host named Variable with the value of local host. In a strength, we're gonna create a constant called host name all one word, and then it will be a shrink with a value of local host. Next, we have the concept of a port. A port number is a way to identify our particular server program on the local network as a running process. Another typical development port number is 3000. So let's create a port variable and then have it be 3000 great with our host name and port . Now we're ready to create our server. So let's create a new server constant, and then we'll store our server object in this constant to create our server. We use ah function from http called creates ever given to us through the H T T P module and now stored in his eight TV object. So we'll set equal to 80 p dot create server. Call that function by using its parentheses. Now create server takes one argument, which is a callback function that allows us to specify different options for the server. This callback function has two arguments itself called wreck and rez, which are short for an incoming request and the response of our server. So it was providing an arrow function and then, for its parameters, will have our wreck and rez objects. Let's expand out this function as well for our server that's immediately respond with a message by using response dot end or resident end to respect our perimeter. The UN function for the response object signals to our server that we have finished all configuration. The end function itself takes in the data that we want to respond with. Let's respond with a shrinking the greets a user and says, Welcome to note several called the end function within this response. Rez object. And then we could provide a string that says, Welcome to note. You can put an exclamation point to make all the more exciting. Great. We're nearly there. We have a server configured. Now we have to start up the server to allow it to begin accepting connections on a specified port and host name. To start up the server, we wanted to start listening for request. As such, we have the server dot listen function. So let's call the server. Listen, function that our server has, and one way to configure this listen function is by passing in the port and host name as a first two parameters, so will provide the port, which is 3000 and they will also provide our host name, which is our local host. Strict, then, for the final parameter will provide a function that will serve as a callback that fires once a server is actually listening. Let's provide a function that logs a message to the council that the server is running. We'll also use an E six template, literal string made with back ticks to efficiently love that we're listening at our host name under the specified port number. So we'll provide our callback function with arrow function, and then we won't have any parameters for this call back. But we will have some code that says council dot logged the fact that and we're using a template string here so we can achieve string interpolation more quickly. And then we use the dollar sign, Curly Brace syntax to insert variable. So we're going to say that we're listening at the host name or rather, that were running at the host name. And then we'll say after Colin that we're also doing so at the specific port number. Great. With that consul dot log down, we have our code ready to fire, head back to the terminal and within the first server directory. Let's invoke the note program and run our index program that we just created. So this tells no to start the index dot Js file and then we have our message that the server is now running at local host poor 3000. So it's listening to test this. Let's head to a new browser window. Here we are, and then we're gonna go to local host 3000. And as we do so, we have a message that greets us that says, Welcome to note Perfect. Our first notes server is working. Congrats. Before we move on, though, let's take one more step to get further in line of what's typical of a node application project. Usually to start up our app, we use a command. NPM start with the start command and PM will look at this script section of her package Duchy son Foul and run whatever is listed next to start. So it's head to our pacts. Touchy some phone find package dot Jason and noticed our scripts right now only have the test. Well, we can add a 2nd 1 can be sure to use strings. We'll have start and as the value will have the command, we entered into the command line to find the application which was node index. And as you say this, we can head back to our terminal now, and with only one command, this extra layer of the NPM start script might feel over the top. But imagine an application that needs to fire two or even 10 different commands to fire up the server. Well, we can capture all of those commands within the start script for NPM suddenly and PM Start is looking very convenient, plus many host providers for node specifically, look at NPM Start field in order to know how to properly fire up the application. All right, within our command line. Now let's stop the server by doing control, See? And now, rather than using note, Index will say NPM start. And as we do so we see that we're running our note index command and then the server is listening. And again, if we hit our browser, we see on a refresh that again we have Welcome to node on local host 3000. Perfect. Our server is listening on local host 2000 as normal. Let's move on and continue improving this first HDTV server with note 7. Optional: HTTP and Web Requests: Let's use a moment to go over http and Web requests to start. Let's think about the Internet and data on the Web in general. On the Web, companies and organisations store large databases of information. They have a list of users, collections of folders and massive troves of files. We can access that information but visiting their websites, which allow us to access pages where we can view that info. Whenever we access a page on that website using our Web browser, we are fetching AFA a page or picture or group of files, pages with pictures and so forth to do so. We access those files to the browser through hypertext transfer protocol. Http. As a protocol or official system of rules that govern the Web, hypertext transfer allows us to use the request and response model, meaning in the request and response model. We send a request for files from some organizations Web server. We get back a response for the foul picture or whatever we want. These requests are called http requests methods, and there are a few different ones. Now there are two primary http requests methods get and post a get request. Asked for data from the Web server. You most commonly make debt requests when you visit a page on a website asking for the page to be served. A post request, on the other hand, sends data to the Web server. A common post request would be sending a new item to a social media feed, such as a photo for Instagram or Story for Facebook. We Post dated to the Web server, which then let's backs the data through other users following get requests or our own subsequent getting request for the updated list with are posted data and information. There are other http requests that are used, but let's comment. For example, there is the delete request, which more specifically, deletes a resource from a Web server. We use these whenever we make a mistake on social media, for example, and want to take out an item. We perhaps should not oppose it. There is also the put Web request, which, in a similar way to the post request up loads data for a resource. But this one more commonly updates an already existing resource. There is also the head request, which is similar to a get one, but on Lee gets information about http configurations of a resource and not the entire document. The options request but turns the HDTV methods a server reports and the Connect request allows us to get more specialized access to a Web servers. Shared network of resource is. Finally, you often find a list of these requests for a specific organization collected into application programming interface or a P I in a P I or application programming interface for the Web collects a set of these http requests and or to access post, update or delete information from a Web server. With that, we have a pretty solid understanding of how hypertext transfer protocol organizes the access of information on the Web. We also know more about various, where requests and also what a Web AP I entails. Let's move on and continue coding. 8. ES6 in Node: you may have noticed that note allows us to use es six syntax inter applications. You six introduced new features to JavaScript back in 2015 including arrow functions in the back tick template, literal syntax that you see here on line 11 that allows us to contaminate strings more easily. Well, yes. Six has been around for a couple of years. Note has has existed for longer. So in your research, you may see examples of code online that use older syntax. For that reason, it's important to highlight Some of the e six were using already, in this example of a node http server and demonstrate the alternatives in the older syntax . For starters, in her callback function for the creates server function, we have an example of an air function that equal and greater than sign over here looks like an air, which is why we call this the arrow function. However, we could have also created this function using the function keywords in tax from JavaScript , meaning we'll take out the arrow and perceive this with the function keyword, which has the same effect of creating a callback function for us. So if we go back to our command line. Stop our server and restarted. There were so listening at local host Port 3000. Great. Also, if we had to art browser, we refresh, we should still see. Welcome to note as before. All right, get back to the code. Another thing to draw attention to is our temperate, literal shrink when were logging that the server is running at a host name and port to achieve shrink and Cat nation before template liberals. One of the best ways was add strings and variables together so we can take out this. I did a command slash to add a comment slash slash at the beginning of this line and that will allow no to ignore this line. And now let's replace this with a function that does a confidante log again. We have server running at, but now, rather than doing interpolation, since this is a normal string, we can use contamination with the plus sign at our host name. Now we have another string which will be our colon over here, and then we have one final one to add are important Now this doesn't look so bad, But imagine if you had to insert five or six variables. How many times you would have to endure string and add over there regardless, we're going to restart our application and see if it's still logs that the server is running. And indeed it does. Great. We've demonstrated to previous six Syntex differences with their application. Now, if you created JAVASCRIPT applications in frameworks like a react before, you might be wondering why we can't use the imports in tax to grab our modules or rather, why we haven't yet. For example, in our code over here, it might be tempting to replace the code where we require http module with an import statement that imports http from its location. So again, I'm gonna coming out this line and then I'm going to say, rather than constant http equals require the module. I'm gonna grab http in an object called http and use the from syntax to get it from http and you'll find this example in react front and applications, for example. So let's say this head to a command line and try restarting the application. And as we do so, Oh, no. Our application crashes. The imports and tax here is unexpected. Well, why essentially, it boils down to how the require function is implemented in node versus how it import works of Essex it node. The require function is a fully synchronous function meeting when notebooks in APP duchess file it, parses it, and then it's singers and sleet loads the contents of required modules as it evaluates the job script coat. Essentially, the loading of this require code happens first in a specific order. Rather now the imports in tax breaks is order because in Essex, loading of contents from another file with the imports in tax may happen a synchronously so we can't use import because it breaks a note paradigm of requiring modules first. But note is working on a solution long into the future that will support a similar import syntax. For now, we'll continue using the stable require function. All right, with those e six differences highlighting, let's revert back to our original code. So I'm gonna take back our original require function. We're gonna remove this old way of contaminating the string, then use our temple literal also revert back to our arrow function over here, and as we save head back to our server and restarted. Everything is looking just fine. Great. Let's move on and add a little more functionality to this first node server. 9. JSON, Nodemon, and more Advanced Functionality: Let's add some more functionality to this note server. Our goal will be to enable a new endpoint on the server that allows the user to get more specific information. In our case, it will be a page of data in Jason Format, or JavaScript Object notation, which has translations for some numbers, meaning it will show a number spelled out as its whole word. No, Jason is not that far off from a regular job script object. One key difference is that in its format, every key must be surrounded by quotation marks. We'll make this translation data available in her application through a uber out you are. Well, we'll start with the original local host Port 3000 and then end with the translations endpoint. All right, let's start by exploring the request object we have. Let's start by exploring the request object we have in her coat. So go back to the code we received in our create server function. We had this request object, so let's go ahead and at a constant log of that request. And before we start our serving out in our command line application, we're going to insult a tool to make our development lives a little easier. It's called Notebook. No admin will allow us to automatically restart our notes server whenever we update application with a safe, this will become really convenient for us as we continue to develop features. After all, having to stop our server and restart it manually after every change could become very tedious. So in her command line, we're going to install known man So du n p m I, which is short for NPM install. And then it snowed mon. And then we're gonna tag the same dead flag with dash, dash, dash safe and then dash death. The Save Dead flag distinguishes node mont from dependencies needed in a production version of the application. Now it's at a new script to our list of scripts that will specify for us a development start up version of our server. So it's head to our package Dajae son file. We're going to add a new key called Death and the value will be invoking the node Monde startup. And then we're gonna look at our index program just like start for node index, not a command line. We can run the Dev script now, start is a special one where we can do NPM start without any other options. However, death isn't one of N PM's commands, but NPM run is one of in PM's Commands. And then we can specify are dead script as an option for MP in Run. And as we do so he received that node Mon has started and their node mont is listening to her application. And there it starts our server running at local host 3000. Great. Now we have our server listening. Let's visit that server in our browser and see the log that replace for our rec request object. So here we have our trusty local host 2000. Let's just refresh it. And now we look back at our command line, and here we see this giant huge data dump in her application. This represents all the information stored in that request Object. No, certainly gave us a lot of info to work with, which gives us a lot of power when interacting with the front end in the back end of our Web application. So feel free to scroll through the entire thing. There's a lot to attach to you. Overall, this data represents the information that was sent to us through the browser for our purposes were interested in a euro l field off this request object. So interco down it's actually put this terminal in the left hand side and then our code on the right hand side and take out this tree over here with command being so that sidebar goes away. You know, in her index such as file, we're gonna grab the your l from our request object by using E s six destructions in tax. So rather than writing constant your l equals request that your l we can use a shortcut rather your out and make a local euro variable for the function and then set its value to the request dot your l value that is, within this request object. And now, rather than logging our whole request object, we're gonna log the your l. Let's take out the first cause of that law because we don't want huge data dump anymore. And as you save notice that the node Mont Runner listen for that save. And then we started our server and now we can see this year l as we do so in action. So let's visit local host 3000 again, this time at a translations in point. And as we do so looks like we're not getting a response of data. That's because we haven't properly handled it yet, and also because requests isn't defined. You guys probably saw that we're going to need to do a your out of wreck, so let's go back. And as we reload, we still see Welcome to Node. But we see that our translations over here has logged to the council. Awesome. We also get this request for the faith. I called that icon Bob. This represents that icon in the Ural Bar, or tabs for Web pages. So notice that browsers automatically ask for this file by default from a Web server. Now we're not providing a favor. Icons that I co file at the moment, but you may or may not have a favor icon like this one appearing in the local host for you Already, you Bowser might have previous browsing data stored in its history because of that, it uses previous favor icons it found from previous abs at the same mural. All right, never. We had the euro log in to the console. Let's use this. You're out to add more functionality to our server. We know that we're able to receive the translations your L Now now, in the case of the translations euro, let's send back some different data. Let's create an if statement the captures the translations, your L and then ends the response for the server with some test data to represent translations. So let's say if we find translations, so if are you are l is equal to slash translations, which it should be, as we're seeing in our terminal over here, then we're gonna respond with different functionality. So it's a rez dot end, and then we're gonna send back a shrink that sends translations. So you say this node ban restarts or Nouman rather restarts or application, and now we can refresh. He refined translations is logging instead. Great. Let's extend this functionality and have the data returned some JavaScript in the form of Jason rather than this strength to begin. Let's create an object that represents our translations for some data to work with what's making object called translations, with some conversions for 12 and three. So we'll say our college translations is one key is spelled out. One for two key. It spelled out its two. And then you can probably guess three spot out is three. Nice. Now we have to use this response. Object now to send back this translations object in Jason for first off will set a header for the response. A header identifies to the browser. What kind of data were sending back in our case Will set the header with the set header function within this response object. The first argument is the key of the header We want to change. The value is a specific type of header we want to specify. In our case, the key is content type. The value is application, Jason, both s string values. So rather than raised up and we're gonna have a rez dot set header. So raise doubts that header The key is content type, which has a cool casing of upper case characters and then separated by a dash. And then the value is application slash Jason Now for the actual transmission of data to send back data through the response, we write a stream of data through it now. What is a stream of data. A stream is a sequence of data that you can continually add by writing to it or grab data from it by continually reading from that same stream in the back end of node. Many of notes objects you streams to make readable and rideable data. This means that send information through a response object will write to the response stream. So we'll say, erez dot right? And we want to write our translations object. The stream itself, though, take strings as his parameter, which poses a problem since our translations is currently an object. But not to worry, we can use the Jason dot string if I function to turn this translations object into a complete string representing Jason, so Jason is a global variable in note. Then we can access the string of five function and then passing our translations. And now this should be the stringed version of our translations. Object. Then we'll add our semicolon at the end of this to complete our line. And now let's revisit our translations and point it as we do so. And what we find is our transitions object in Jason. Form me now we also see the welcome to note ending response. That's because the response dot right method doesn't completely end the whole response. If we don't want that welcome to know, to show up we can end with rez dot end just like so, as we do so and refresh here, we'll see that on Lee Are Jason object is represented. Great. We just explored some more complex features of the http server module that is needed to note We've also touched upon the content of routing by specifically responding to the translations you were. L in her application will want much more powerful routing features in the future, but the code for this will become increasingly complex. If we try doing this with native note objects to aid in this process, no, we can use a framework called Express, which will specifically help us to create more complex node server applications with great routing methods. All right, let's move on and keep coating 10. Optional: the Event Loop: you will often hear that no Duchy s has the ability to execute multiple operations concurrently, there are many approaches in computer science to achieve this such a spawning multiple processes to execute different pieces of code at the same time. But let's explore no DGS is solution. The event loop dot orgs has concurrent execution. Let's clarify what we mean by concurrent execution in programming. Current execution refers to when programs can execute multiple operations concurrently at the same time, rather than sequentially one after the other. This can lead to great improvements in performance since time this saved when operations are not blocked by each other. For example, a sequential pro ban could be significantly improved if it has operations after are particularly slowly. For example, if it executed the slow operation concurrently in the background, it could still execute the following operations in the forefront. So how is this concurrency achieved? First off will re raise the idea that note is known. Blocking meaning http requests database operations reading and writing from the computer hardware is disk for data through Io's are non blocking operations in the run time of note . While it's executing these operations are asked to be performed, given a callback function and then the run Time moves on to do something else, which enables the runtime to continue executing coat once the operation has completed sometime in the future. The callback function that was originally provided fires. This cumulative effect makes the execution of these operations concurrent in nature. Now let's extend this idea to the note event loop. Well, the Java script Runtime is executing code. It waits for operations to complete and for call backs. If I, along with each of these callbacks, comes with the message that is cute that identifies it along with a call back now, JavaScript pulled all of these messages into acute. You can think of the Q like a line at the D. M V. It's organized in a first in first out minutes, meaning as more messages get into line or in the queue. The first message that entered will be the 1st 1 that comes out now. The basis of Notes Event Loop is that it's a cute it pulls for each next message, encountering them in a line it executes full that callback one message at a time. Now let's extend this idea of concurrent operation with a metaphor that will help us illustrate this concept of the event loop and ability to execute code through it. Concurrently, it's called the Masters and Butlers Metaphor. So it goes like this. Every morning the master wakes up. The day starts with a head butler, asking the master for a tasks to do. The message may give the head butler one task or multiple tasks, and the master then goes back to sleep. Head Butler then divides up those tasks among the other butlers and then they start their work. Once a butler complete the task, he lines outside the message door to file a report. The master then welcomes in one servant at a time to listen to the report. And based on the report, the master may even give that butler more tacit care. Yeah, but in this middle phase over there, the master had different multiple servants executing code at the same time. And in the end, the all que up in line to send back the report to the master. All in all, in our case, the master is like our javascript runtime able to delegate tasks Concurrently, the butlers are non blocking Io operations in the event loop is that Q of butlers who have completed a process and need to report back to the master. In some, thanks to non blocking IO and the Event loop, we can achieve concurrent execution in no dot gs. 11. Express: what is express, as defined by the Documentation Express, is a fast, UN opinionated, minimalist Web framework for no Dutch. Yes, all right, let's unpack those terms. First off expresses very fast due to its minimal nature in implementation. As a result, we can access powerful features like routing and responding to different data formats at a very low cost. Expresses un opinionated. There is no one force right way to write code for your Web framework with Express. Therefore, express allows for a lot of flexibility. This contradicts other frameworks like, for example, perhaps ruby on rails, which is commonly used for AP eyes that want you to write code in a specific way most of the time. Finally, as a Web framework expresses, greatest strength comes in creating a P eyes for Web servers. You could think of a napi I as a collection of related your L's to grab information from a server and its database Express contains tons of methods for setting up HDTV, get methods, post methods, not to mention the other ones, like pageant early. So creating a P I with express becomes a lot more straightforward than Native Note Express also contains nice features like routing, which allows him to find endpoints over applications and AP eyes in order to have more control over what information we send to our requesters. All right, now that we've had this quick intro to express, let's move on and build some cool Noticias servers and express AP eyes. 12. Setting Up the Fortunes API: Let's sit up our first node and express application. This app will be a server in the FBI. The list out fortunes, based on a user's request by fortunes, will give back interesting data like predicting the future and a lucky number to the user. All right, to set up, head back to your command line and find the director you're using for your node projects. So we want to be in node Post Press now. Within note, Post Breast will make a new directory called Fortunes FBI. When we combine the words together, we're gonna use snake casing or connecting the words together with Underscores. But you can use camel casing as well or capitalizing the combined word or whatever convention you're comfortable and familiar with. So make a new directory with M K. Dirk AnAnd, and then we'll say it's the fortunes. Underscore a P I. No, let's change into it to navigate in and then once were in here. We're going to initialize our project with the NPM in its command and PM in. It usually takes us through a series of interactive commands to set up a package da Jason file. For us, however, we can always change the answer of those questions later, but editing the package dot Jason file. So let's speed up the process by using the dash. Why option for the command to go through the NPM minute process? Non interactive Lee meaning We're going to skip all of those questions, so we're gonna say npm in it. Then afterwards, Dash. Why great. Now we have our package dot Jason file and her project name Fortunes A P I. Before we open up the project in our code editor, let's install to external dependencies for this project. First, we'll install Node Mon as a development dependency. If you recall known Monde was a nice addition on top of node that allows us to have a deal . I've development server that refreshes are note application whenever we save an update of fall. So let's install it with the Save Dead flak. We can also use NPM I, which is a short cut for NPM install. So we're gonna use NPM. I we're saving known mon as a development dependency. Now we're installing Note mont as a development dependency because we don't need it in a production environment. However, one dependency that we want in both our development and production environments is the express framework. So when we install express in PM, I express, we're gonna use the regular say flag. Great. With that, we've set up what we need to start working in this fortunes. A p I. Let's begin writing the code for this application next. 13. JSON for Fortunes: now that we have our project created, let's open it up in her code editor and begin building this fortunes a p I, by the project in the command line and then open it up. I'm going to use a visual studio code shortcut to open this one. So that's code and space dot So let's pull it up over here. Going to make this full screen nice at the moment. You should have a known modules folder for all of our modules to support Now, also the Pakistan Jason foul we created with NPM in it and also a package dash lock Dodge a sample. You can think of this as a super extended version of the package dot Jason fall where every single module dependency is explicitly listed out along with its own dependencies. You see, just because we Onley installed express in Nordmann doesn't mean we Onley exult, expressing no mom after all, either known one or express meet other modules to be installed themselves as further sub dependencies The package dash lock Dajae solve all lets out those install dependencies We have now in our module or rather are known models full. All right, Now that we have a grasp of all these files within the project. Let's set up our A P I. With some data for the A P, I will be sending back different Jason objects that represent fortunes based on the user's request to collect. All these various fortunes will store them in a file called Fortunes dot Jason for the war to keep our project clean and organized. We'll also start this data in a new folder called Data. So let's make a new folder called Data, and then within that folder, we're gonna make a new file called Fortunes dot Jason. Here it is data slash fortunes dot Jason. Great. Now, as a Jason formatted file will be writing a file whose contents represent JavaScript object notation, which can contain job escaped objects or a race. There's an important difference to consider when we write this, though, in this format for our data, we surround our object keys with strings. All right, our collection of fortunes will be contained within an array, so let's start with some brackets then, for each of the items in this array of fortunes will have a job script object to represent an individual fortune for a back and service. It's typical of each item to have 90. Let's give this first object, and I deaky surrounded by a shrink or rather, with industry. And remember, we surround the key with quotation marks to market as a shrink for the first object will give its I d. One nice. Now let's think about some data we would want for each fortune object. Each fortune should have a message. Key beans Fortunes often predict the future, after all. So for the 1st 1 let's give the user something hopeful. How about a message that says so? Here we have our message key and the message is, love is around the corner. Nice. Feel free to put any message you like rather than this to make this fortunes object more interesting. Let's also give it a lucky number as well as a spirit animal. So for this one, it's lucky. Number will be 12. You put anything you like in the spirit animal will be doc Nice. Now we have one fortune object. Let's replicate the same thing for two other objects. Increment the I D keys and changing lucky number and spirit animals. So I'm gonna Go ahead and copy this. Make sure you have a comma after the 1st 1 as well as the 2nd 1 Now, this idea should be to this one. Should be three. How about the message for the first? Or rather, the 2nd 1 will be. You will find a great treasure. Let's change this. Number 2 15 in a spirit animal will be lying on this guy. I mean, how about this? One person will give you great advice. The lucky number for this one will be 30. And how about bear for the last one? Awesome. Feel free to add as many fortunes as you like to this array for development purposes. Three should be enough, though with that, we have our back in data for our fortunes. A p I. Let's move on and create an endpoint to actually serve up this data. 14. First Express Endpoint: now that we have our back end, let's right the express ap I around the data to serve it up. First, let's initialize our project with an index dodgy s foul that will represent the root of our JavaScript node project. So good and create at the root level, the index dodgy as far so not in the data folder, but within the root fortunes. Ap I folder in node the index dot Js file is a typical starting point for packages and models. So it follows that creating our server with an index dot Js file is a good choice. Now, our goal with this index dot Js file will be to create a Web server that allows a user to make a request for the fortunes and get the data that we defined in her fortunes dot Jason Fall To create this Web server, we now have the powerful web application framework in node called express. So let's require express from its designated module and store off the result in a constant also called express. We're gonna make an express constant and then require the express module. What does this express concert now represent? This required express constant now is a function that allows us to create the express application. This function, when used, contains many configuration options in the resulting object it creates. We'll explore these various options soon, but first we have to make our express application object by using this function. So let's start off the result of calling this express function in a constant called app, since after all it creates are expressed application Nice. We now have an express application ready for us to configure. Now this application object is actually very powerful. We can already use it and it's custom methods to create an actual http endpoint with one function. Unlike in our previous native code example where we had to achieve routing for a get method by checking the Your L Express provides a very nicely named get function that allows us to create get methods for the FBI. So let's call the get method on this app object now that we have Suplicy app dot yet which is the get function. This get function has two parameters. The first parameter represents the end point for a P I that we want access. Recall that by an endpoint, we mean that the last part of the URL, for example, in facebook dot com slash photos. Photos is the input or in facebook dot com slash events. Events is the end point. So for our fortunes data, perhaps it makes sense to have a fortunes endpoint to stay online with a P I behavior. We also begin the naming of this endpoint with a slash to represent that were a pending this to the end of our Europe. So we're provide a string that begins with a slash and then argue fortunes. Then, for the second parameter, we provide a callback function. This callback function will fire when the fortunes endpoint is hit in the A P. I for this callback function will provide an arrow function. It will also have two parameters called wreck and rez, which represent the wreck the rather in the request and response object. So here's our era function and then has two parameters wreck and rest again. What are wreck and rest? Well, they're short for request or wreck and response Arrest. The request object represents any data sent by the user to our A P. I. The response object has further custom options to allow us to respond to the user with specific data. We'll explore the request object in detail later. Also, before we send back any data with the response object, we have to do a little development work at a concert, that log to make sure that this fortune endpoint is actually working once you start up our actual application. So within the body of the callback function, let's have a consul dialogue that says, requesting fortunes. Awesome. Now, before we actually attempt to hit this endpoint in a running version of the application, we still need to make a call to the listen function on this application in order to make this server live so right at the bottom after our first get method. What's called a lesson method which will make the server live. Listen function is fine, taking just one parameter, a number which represents what port number to run on without a host name. As the second parameter, the port will attach to the local host. Now it's typical for our development port number to be 3000. Also be using the port number more than once, so let's start in a constant called port right after our requirement of express report is going to be 3000. Then we provided as the first parameter to listen. So let's give it the port, then as their second parameter. Let's revive a callback function, which will log a message in her console that the server is listening on our port number. We'll use a template literal, shrinking too easily. Insert our port number so we're gonna have a callback function with an air over here. And then it'll point to a constant log with our template literal, which is the back ticks next to the one key listening on port. And then let's insert our port number using the dollar sign Curly Brace syntax. There we go and notice that when you use an era function, the only spans one line. The re use of curly braces is unnecessary. Great. We're nearly there now. We just need awaits easily. Fire up the server from our command line. We could use the command note index right away, but its conventional to provide a start script in a note project that specifies how to fire it up. So it's head to our package dot Jason. Let's add a new script called start and this will point to node index now. If we use NPM start, it should fire up our application. However, as we're developing, this would mean we have to stop the NPM start process and restarted every time we make a change. Rather, let's provide a more convenient script that calls are known Mon package that can act as a live reloading service of our server. When we make updates, will store this one in a script called Death and have it points to note Mont Index, which fires up our index dot Js file with a node mon live reloading tool. So that is no Dubon index pointed to you by death. Awesome. With that, let's fire up her application in the command line with NPM Run Dev in the terminal, you want to be in node post breast slash fortunes a p I that we're going to use NPM run command then specify are dead script and they're known one has started sleds visit local host Port 3000. So once we hit our fortunes and point on our server notice that we're getting local host last fortunes we get requesting fortunes logging to our consul which is performed by the code that we have right here in our get endpoint for fortunes. Nice. Now you'll notice that even though we're logging to the consul, our browser endlessly hangs on the information and try to get whatever we're trying to get based off of this request. Well, unfortunately, we're not currently sending back any data, so let's figure out how to display some data on the browser. As a result of this get method and request. Let's replace the concert log with a function called Send. The send method is available on the response object or represented by rez that we have in our callback function. As signified by its name, the send method sends back the data as a result of the quest. So rather than called Sadat, Log will have send method on this response. Object as we say this, our service should update and let's put this side to side so that we can see it's actually updating once we make changes. All right, so we say that and then we head back to or fortunes endpoint over here and there we go. We have requesting fortunes in our brasilena. Great. Now we're also just returning a mere string of data. However, ideally, we want to return that whole or rate of fortunes. Now, before we can send that data, we need to have access to it. Within this file, that means we're going to require it in the top as a module in a constant called fortunes. So it's a constant fortunes equals a requirement of Let's look at this current directory, notified by dot, slash look at the data folder and then find the Fortunes folder within that. Now we could replace a string of requesting fortunes with our fortunes constant that we have. However, the express response object comes with a more powerful method, specifically created for responding and rendering with Jason Formatted data. This method, rather than send, is called Jason. So let's return. Our fortunes object with the response dot j salon method. So we're sending rez dot Jason and putting in our fortunes that were required. You say this noticed that it reloads. Let's reload this, and now we get our whole body of fortunes array in our browser. Awesome. We just created our 1st 80 TV method on this fortunes AP I Excellent work. Let's move on and continue improving upon this fortunes. AP. I built in Express 15. Optional: Startup with an Executable: As you research note and express applications, you might see that this starts get points to a file in a BIN folder called www. As you continue to create note applications with expressing the future, you might come across tools like express generator, which also automatically create this Been slash www. Far this been W W file is an executed will file, which takes care of starting up the note application for our purposes. It adds another layer in between our application code in the index touch es and the code that actually fires up our application. However, it can be a convenient way to set up our node and organized the express application, since the BIN folder may contain other excusable files, which can define other ways to start up the app, perhaps in a testing environment or customized setting. So let's create this bin folder at the top of her application right next to data, we're gonna have a new folder called Ben. Now, the name BIN is inherited from the naming convention of most operating systems themselves. For example, in Michael S or Lennox and even windows excusable files live inside these been folders. Now, if you're unfamiliar with the difference between an executed will file and regular fall. You can think of it executed a file as one designed to perform a specific function on the computer. It's basically a rentable program Now. The execute herbal is usually unreadable as code, since it's already been compiled into machine code for the computer to execute. Hence its execute herbal. All right. Within this bin folder, let's create art. Www Excusable. So let's make a new file within here, and it will literally just be www with no extension. Awesome. Now let's restate the purpose of this excusable www. This executed all file will take care of starting up our application. That means we'll move our code that actually starts up the express application and hasn't listening on our local host port instead of appear. So let's grab the lines over index dot Js code that took control of setting up the port and listening for application and put it within this www excusable. So let's grab the port and cut it. Actually, we'll save this file to no longer have the port. And don't worry, the development server is gonna crash in the background. That's because we haven't fully set it up yet. We also want this whole listen function as well. So in our Www, we have our listen function in here, too. Great. Now, if you look at the code notice that we're now using an at variable that doesn't exist. We'll need a way to grab that at variable and require it in order to require, though we'll need to make sure our app in the index dot Js file is terrible or, in other words, exported. So its head back to the index RJ's fall and that will complete our file with a line of code that declares this APP object as the export. To do so will utilize some special node syntax called module DOT exports. The takes care of setting this app constant as export for this module we're now creating. By using module dot exports, we can expose the app as a module itself for other files to require and work with. So we'll use module that exports and set it to our overall app. Instance. Great now that we created in that module within this index, Thaci's FOB, the name index dot gs doesn't appear to make that much sense anymore. So let's rename our file to abduct Yes, to make it representative of the fact that is hosting the APP module. So rather than index RGs, we're now going to call it app. Dodgy s nice. Now you can acquire at the top of our www execute will file within the bin. So within our been, we have www and at the top, let's a choir and we're going to have to look back one directory and get our app module Now . One more thing before this executed is ready as an executed ble, we'll need a way to tell our computer that we're creating a note. Execute herbal. To do this will create what is called a shebang line at the top of our execute. Herbal again, a shebang line at the top of her executable. A She bang is a character marked by a combination of the number pound sign and an exclamation point, and it's used to tell our platform were to find the specific way to interpret are excusable . So let's provide the line that identifies is excusable and tells our computer to use a code interpreter with node executed to the top here we have our pound and our exclamation point , which is the she bank. And they were gonna look at the user folder that is global to the system. Look at the global Been in the system. We're gonna look at the environment folder and tell it to start up note. So it's slash user usr slash bin slash end and then note. Great. Now we have this execute already. Once you've declared this as a note excusable, let's update our patches dot Jason Start and Deb script. Now to execute this been w w file rather than the index file they got renames after GS and no longer contains are listening coat. So within package dot Jason, we're going to start. I mean, look at dot slash been www in the node mon got slash bin slash www Now let's go ahead and restart our entire server, clear it and then redo NPM Run death in our fortunes ap i directory of the command line. So as it goes there, it starts dot slash been such www And we could also check in our browser If our data still appears on a refresh and nice. All there as usual now that we have inexcusable taking care of starting up our application . Our code has become more module arised with an abductee s fall specifically taken care of creating the express app and execute herbal That takes care of starting it up. Great. Let's move on and approve upon this fortunes ap I continue exploring express. 16. Get a Random Fortune or One by ID: Let's add two endpoints your fortunes AP. I now one will get a random fortune. The next one will allow us to get a specific fortune, but requesting it, it's I D. Let's tackle the 1st 1 and at new method that will allow us to get a random fortune. Now it's typical for AP. Eyes to use sub routes or name spaces were getting for the data based off of a previous endpoint. So rather than something like a whole new fortunes underscore random in point Recon nest a random and point after the fortunes route or name space or after the fortunes name space to represent getting random fortunes. We using get method for our express application once more. And this time we'll use the Necid random endpoint under fortunes. So we're going to say on a nap, Doc. Get off slash fortunes. And now we have this fortunes name space. Let's hit the random endpoint on top of that, and then we provide our familiar wreck and rez callback function with the wreck and reds response objects. Great to make sure that this random endpoint message under Fortunes Works will have a causal dot log of requesting random fortune and check if it actually logs in our browser. So it's a constant log requesting random fortune. Now, if you don't have the server running, go ahead and fire it up. Recall that the NPM run Dev script will create a live reloadable version of the application with no DeMont. And with that, let's check it out in our browser. So this time fortune slash random. Now we won't get anything back yet because we haven't responded. But if you look in our development command line, we see requesting rent a fortune indeed, logs to the council rate. Now we can write the code to actually send back or random fortune object. First Up became access our random fortune by using a random index for a fortune object in this array of fortunes. To get this random index we use the math at random function returns a decimal number from 0 to 1, so it's a constant random index equals math dot random, which will give us a random number from 0 to 1. Now, by multiplying this number by the length of our fortunes, AP I we should get something up from zero up to the length of the fortunes AP I So let's multiply it for the length that we have in our fortunes. A p I great. Now we have a random index. Now Mathare random returns a decimal number, so multiplying it by our length will still be a decimal number. So in order to make it a nice round number, you can floor this whole result with the math dot floor function. And, by the way, math and math, our global variables within note and JavaScript Great. Now we have a random index. So let's access the random fortune by using this index to get an object from the fortunes for Ray at it will store the random fortune in a constant called our fortune. So let's make a new constant called our fortune access the fortunes array and then passing our random index finally will respond with this. Our fortune object as Jason for the request Self will respond with reds dot Jason in passing are random fortune. As you say this. Try our newly revised fortunes random and point in the browser, and as we do so, notice that we get a random fortune. Lets try again. This one had the idea of one. This one has the idea of 31 Let's get to There is too great. As you can see upon multiple requests for a random fortune, we get all three of our different fortune objects from our data file. Eventually nice before we move on. There's some code improvements we can make, though to this get slash fortunes slash random function. Usually it's not that useful to starve code in a temporary variable if it's only used once , so both are random Index and our fortune object are only used once so we can in line everything by placing the accessing of the Rendon fortune all within the rez dot Jason method. So first off, we can take out this whole random index and place it within our fortunes or a And there we are. We're gonna access a random fortune, and now we no longer need this. Our fortune weaken, grab this whole thing and passing as the parameter to RJ's on and delete this our fortune. We can also take out this confident log, and suddenly we have a nice one line function. As you save this head back, let's retest the endpoint. And indeed, it's still working just as usual. Great. Let's create another convenient get endpoint for singling out fortune objects. A pattern you might see with many other E P eyes is the ability to access an item of data by using its i. D. One strategy for requesting this data is to use a nested route as a parameter in their request, meaning if we want the object with the I. D of one within fortunes will make a request to fortune slash one. Similarly, for the object with the idea of three, we should make a request for fortunes slash three. All right, let's add this capability with the get method that also has a necid route for fortunes. So I'm gonna add and you get function with our usual call back with a request and response object represented by wreck and raise. So here's our callback function and our endpoint. And now, for the actual in S and route parameter, we can use a special kind of syntax that express for rides for us. We'll use a colon to signify that this necid route should be passed as a parameter in a request object. So after the colon or rather after the fortunes, we have a slash and then we have our colon. And then we specify that we're now going to check for an I D represented by a number. Awesome. Now that we have this end point, let's consider the effects of going to fortune slash one or fortune slash two under server Now, when this happens, pass the value of one within art request object under the I D variable, we declared in a route strength. These parameters within the route will be stored in a Paramus object under to the wreck object. So let's constant love that request. Stop Haram's object and check it out. It's called adult log wreck dot Krems and see what it has as we say this we're going to visit fortune slash one. Now, as we do so, notice that we get an object in our development environment. That is, I d pointing to a shrink one Nice. Now that we see this logging, we know that we can use it. So let's write the code to find the appropriate fortune by its i d and respond with it as Jason To find this fortune, we use helper function on a raise called find. So we'll use fortunes dot find and find takes in a callback function that allows us to look at each item individually within the array by storing it within the first parameter of our callback. So we have a fine call back, and now we're gonna operate on each fortune individually and represented as f Now, within this F parameter which will represent an individual fortune object, we can return the first fortune object that we see whose I d matches the I d. We have stored within our request operations. So we're gonna look at each F i d and then check whether it equals our request. Dup Haram's dot i d. You can also take out this culture dot long now notice the use of double equals rather than triple equals. Here, the tropical equals comparison operator in javascript makes an additional type check which would not work. In our case, our store Jason Data, uses numbers. What are passed I d parameter is represented a shrink, so the triple equals check would return false because the types wouldn't match. However, the double equals comparison operator does not make this extra type check and can see a string one as equivalent to the number Type one in JavaScript. All right. With this code in place, we should now have the found fortune. Since find returns only one object, the one that it finds first. As a result, let's respond with this data overall as our Jason. So we're gonna spawned with this entire fortunes dot find as Jason. All right, nice. Let's revisit the A P I in her bra. Xena, we can check for 14 slash one, and there it is slash one. How about two? Yep. We got two and then three. Excellent. We're getting all three of our fortune objects as you visit them through a necid route, friend. Great. We've now added to powerful get methods to our collection of interactions within this fortunes AP I with the random endpoint and the Necid route. I deep remember, let's move on and explore the other 82 methods and figure out how to add update the data in the application to make this a p I even more powerful 17. Fortunes Post Method: Now that we have a couple methods allows to grab data from our fortunes ap I Let's interact with our FBI in a new way. This time, we'll give the user the ability to update all of the back and data and give it some new fortunes to give this a P. I knew data. We will make a post request. A post request is a related method to the http get requests method that allows us to send the AP isom data through a request object. Now, let's consider the form of this incoming data. The incoming data will come in the form of Jason to make it easy to interact with. However, in order for no Duchy s to handle this incoming Jason Data, we'll need some way to smartly understand and parse the data. This is where the concept of parsing middleware comes in for incoming data to the server. In terms of computer science, middleware is a general term that can often mean the bridge between applications and data to establish a common form of communication in our case, the middle where it will allow us apart. Jason, Luckily, we can get this middleware fairly quickly but installing a module that takes care of setting up the middle Where for us in express said her command line. Go ahead and stop the script. Let me enlarge this. And now we're going to insult a new module called Body Parts. So we're gonna use NPM I command. And then that's body dash part, sir. And then we're going to use the say flag since we wanted as a dependency on our production and development environment. So now that we have that installed, we can use it within our ab fall. So after express its install, but rather require this module and use camel casing for the actual constant name. Require it through its dash taste, body parts, er, module, location and every habit. Great. Now we can tell our app to use the body parts or Jason middleware function that is now stored within body part, sir, on this app. So we're gonna say at go ahead and use by using the use function. The body Parsa thought Jason middleware function. This should take care of allowing us to receive and parts Jason data through incoming requests, objects. Let's move on to creating the actual poster quest for making new fortunes within our FBI to create this post method, we use the same syntax as or get method. Except this time will call dot post on our express application for our parameter will post to the fortunes endpoint. Yes, you can have the same path or endpoint as the get method. Although they share the same endpoint, they'll be distinguished from one another through the type of method that it's interacting with that end point. So, after all, ever gets, let's have a post to the fortunes and point. And then we provide the familiar request and response parameter callback function the fires Once we hit the fortunes endpoint. Now we'll actually want to look at the request object. This time, this request object will give us a body of data related to what the user sends in their post requests to the A P I. So before we start interacting with it, let's make a consul dot log of the request body to see what it looks like. So it's constant log on this repressed object, the body, and now make sure to have your server running in a command line window. So if you stopped it. Go ahead and jump back to NPM. Run death, and as you do so, the live development port should start up. Now we get to the matter of testing this post in point. We don't have the immediate ability to visit your URL on a browser tab this time to make an automatic get request. Post Request are usually performed through code behind the scenes in a front and application within the code when you use it on the Web, not rather than coding an entire front and app to perform this post request, we can use a command line to specify a poster crest with the Curl Command. So let's go to a new tab on our command line so you can press command t within terminal. And now we're gonna make a new post oppressed by using the command line. We're going to make what is called a curl request. We'll use also the capital Dash H option to specify a header for this Girl Quest header helps US server identify what kind of data is coming in through the Quest header with the key capital content Dash Capital type in the Value Application slash Jason will identify the upcoming data as Jason. So we make a curl. So that is curl and then dash Capital H and will provide a string that the constant type is application slash Jason. Then we'll use the Dash X option to specify what kind of requests were making. In this case, it's a post request. So Dash Capital ex Post, then with the D option, we can start specifying some data for this. So after Dash's ex post, we can specify D, and then we can provide a data in a shrink with single quotes that represents the Jason we want to send. So let's send in perhaps something that represents a fortune. And remember that we want this to be in the shrinking, but it will represent Jason. So have a pair of curly braces within then Our first key is message for that, Jason. The message will be hello will also give it a lucky number about five. And this time the spirit animal will be dog just like so and finally with specified euro to hit overall for this post request. So we're gonna hit http slash as local host slash slash local host and important 3000 slash fortunes. All right, through all of this, hopefully you can see it. So at the end over there, it's 80 defeat. Colon slash ash, local host Colin 2000 slash fortunes. Let's run it. And as we do so we get an unexpected number. You guys probably saw that I forgot to put a colon after lucky number. So luckily, we do get a nice air message. And this time, if we head back to our development, Consul, over here we find that the logging is message. Hello? Lucky number five Spirit Animal dog. For good measure, we can make a post request one more time. And as we do so again, we get the same message logging to our consul because within our post handler or concert dot logging the incoming request body. Great. We find our fake data logging in the command line. Now we're ready to write some code that uses this data to add to this Jason file of fortunes. First off, in order to add to our fortunes, file of data will need to create a new fortune object that we can add to our array of fortunes in the Jason file itself. Luckily, we have three of the four pieces of data we need for a fortune from our request body. So it's use in six destruction syntax to declare a message. Lucky number in spirit animal variable with the object data from our request body. So we're gonna grab our message, our lucky number, our spirit animal, and make those local variables and grab the equivalent keys from our quest body object. Great. Now it's to find a new fortune object called fortune. With that data loaded in, we're gonna make a new fortune object in stored in a fortune object in the past in our message, our lucky number in a spirit animal which would make the same keys and values that we get from a request body. We also use music shorthand since our keys and values are identical so we can shorten it. Now we need to make an I D field to complete this fortune object. So let's make a dynamic variable for now, called I D right at the beginning. So here we have our i d, and we won't give it a data yet or rather a value. Yet now it's a sign of value to this number. What should the I d be? Well, we need a new, unique I. D. That is not already being used within the array. Won't. What can we use? One strategy to ensure a unique number is finding the max number already used within the array. And then the new I D will increment that Max I. D. Number. This should always return unique number. So let's get the array of ideas or rather, the array of I DS and store it within a constant called fortune ID's from the fortunes are ray. By using the map method from JavaScript, the mat method returns a new array based on the previous ones. In some filter down data, our callback function returns the new objects we want, which in this case will be each I. D number for each item in the fortunes for Ray. So right after grabbing Oliver Data, let's get a new array of the fortune I ds and then call fortunes dot that what Matt does allows us to return an object for every single one that we have within our original fortunes array based off of a condition. So now we're gonna have unr a of the I DS based off of each fortune object within our original fortunes are right. Great. Now we have each of these fortune I ds Now we can assign our a d variable to the max number of this array of ideas or rather, I ds. Luckily, JavaScript comes the max function on the built in math object. This can take in any number of arguments. So another nice six piece of syntax is a spread operator which will allow us to specify each of the ideas or rather, each of the I ds as an individual parameter to the max function, literally spreading it in. So we're gonna say the I D is going to be equal to a math dot max of spreading in each of these fortune I DS man I ds or ideas Kinda hard to pronounce anyways, Now there's an edge case to consider. If the Fortune I DS array is ever zero, the max function will return negative. Infinity negative. Infinity makes sense as a default for the max function because it's the absolute minimum and any value will exceed it as a max. So it's a great implementation. But this edge case might seem impossible if you always have fortunes, but consider that it is possible to start at the APP with data in the fortunes Marais. Or perhaps he implemented the ability to delete fortunes so we could theoretically hit that negative infinity i d. So it's feasible that all of our fortunes could disappear within the APP. So luckily, we can handle this with a turn Every expression if we find that the fortunes I D is empty will set the I D to zero. Otherwise, we'll use our max function to return the math dot max. So in our I d. And let's put each of these all on new lines to keep this organized. So here we are. Everything is nice. We can also delete these red marks, which means there's trailing spaces. So now we can add our turn every expression. We'll check that the fortunes i ds dot length, we'll say, is greater than zero. If so, we're gonna use our regular math up max function otherwise, in a colon, we can use the zero now notice. Attorney expression is very much like an if statement, we check a condition. So if this condition passes then we go to the true part before the colon, which is the math out, Max. Otherwise, we go to the false section, which is this zero over here. Great. Now we can add to this I d to our fortunes object. But after this whole thing, we're going Teoh increment it by one. So that way we always have a unique number. Great. We're nearly there that we have our fortune object created. We need to update our overall rate of fortunes with the new object. Let's declare underrate called new fortunes. Then we'll set it equal to our overall fortunes array contaminated with our new object. So we'll say we're gonna have a new fortunes constant now and then we're going to come cat , our new fortune object that we just created Great. Finally, let's send back this fortunes data as Jason with the overall response object that we have from our original call back. So we're gonna render our new fortunes as you say this. Let's go ahead and retest out a post request through this curl. So Gwen, run the same curl request. You guys probably noticed that I added extra. That's over here, and we're probably saying no, don't add. That s so as we save that, let's go ahead and rerun are curl request once more and as we do so it's a little jumbled, but notice that we have all over data for our fortunes rendering in our array over here. So we get our new one whose message is Hello. The lucky number is five. And the spirit animal is dog, which is the crow request that we just created. Great. So our new fortunes were created. Awesome. Now notice that our new data, though, isn't here. If we go to fortunes dot Jason. So if we click unfortunate about Jason, Unfortunately, our new data isn't there. Well, we're gonna have to need a way to write our new data whenever we use this poster quest. So in effect, even though we're responding back with our new fortunes array, we still have yet to update the actual file which contains our global source of data for all of the fortunes. So we want subsequent get requests to able to load those fortunes. So what we're going to do is required the FS no GS module, this fs or file system module allows us to run file operations in note. So it's required at best at the top of our code. So above express this time, we're going to get at best and require at best, the module in starting object called at this, then the FX module has a nice right file method that will allow it to replace this fortunes dot Jason fault with our new data for its first parameter, it takes a path and the file name of the data we want to write to you for the second parameter. We provide a strength that represents what we want to write to the file. Luckily, we had the Jason dot string if I as built in method that will convert our new fortunes array into a Jason strength. So it's right our file and point to the data slash fortunes dot Jason file and override it with our stratified new fortunes for rape. We'll do so before our Red's Dodge, a song called So right Before reds dot Jason. We're gonna call Fs not right file. We're going to look at our data slash fortunes Jason folder, and then we're going to send a string ified new fortunes array And as we send this R A p, I should update in our development Council. Now finally, as 1/3 parameter for this function will provide a callback function which will output any errors that the function might have had in writing to the file just in case something went wrong. The parameter will be on air object to represent. Heirs will also confident log the air if the right valve function can't find the file. For example, noble notes call this call that function were provided with and passed the generated air object that it creates. So within here we're gonna have an air object. And if we find it, let's call Sadat. Log that whole air object. All right, let's save this. And what this file writing function loaded in. Let's retry our post request now in our second tad. And as we do so Yep, we have an idea of four posted. And then if we check our fortunes dot Jason, it's stratified, and the Sugar five function doesn't take into account that it should look indented and pretty, but you should see that you have an idea for with the message of hello in a spirit animal off Doug. And if we actually make the post request one more time, our data reloads. And here we have another one with the idea of five. The spirit animal is dog again. Great. Our fortunes dot Jason Array has updated in the file. Now again, signify doesn't take care to include meat indentation. So we have to scroll horizontally all the way to see the new data. What we know that the method is working. Let's move on and continue approving upon this a p I, and add some or requests, methods and coat. 18. Clean the Fortunes Post Method and Use Postman: Now that we completed our post method, we can do a bit of clean up to get this method a little tighter by using vertical space for your code more concisely. For one thing, we can remove the consul dot log of fortunes and our request Body says. Take out this request body Consul. Don't lock Next. We can place the entire creation of her fortune object within the concoct function that adds it to the array of the fortunes that we have. One coating convention that is popular is placing keys on their own line if the number of keys gets particularly long, which were already doing with this fortune. So it's grabbed this whole a pair of curly braces over here in place within, and there we have it in line Nice. That looks a little more clean now, another convenience for development that doesn't necessarily affect our code but will definitely improve our lives as a P I developers is avoiding the curl quests. Now, Karl requests are fun and efficient on the command line, however, we can use a graphical tool called postman to neatly make http requests in a more readable format for us. So if you haven't installed post meant already, you can find the desktop app for Mac Windows or Linux on postman dot com slash aps. So it's look up postman at, for example, Let's zoom in on this and usually the second link or 1st 1 is postman pipe app. So go ahead and click on that, and you're going to want to download the one for the relevant platform and install it so it's go ahead and download the one for Max, since that is this system. Now, I'm going to go ahead and open up this zip file over here, so go ahead and open went done. So once you have postman installed, it should be in your downloads folder. After opening the ZIP file, you could move it to your Applications folder. I know what it's in applications. You can use Spotlight to fire up postman, and once it launches, you should get a window that looks very similar to this. It's gonna take a little toe load now. Once you're inside, you might have to create an account to use postman, so go ahead and do so. But after that, you should get a blank page just like so ready to use it. For now, it's not necessary to make an account, but it's convenient if you want to keep a history of http requests with postman, which would be nice while you're developing. All right. Another thing is, make sure you have your fortunes. AP I running on the development council and listening on Port 3000 that let's try reconstructing a get request to the fortunes endpoint through postman, typing the local host host name only. Get so we're gonna go to http slash slash local host. This time we're gonna look at Port 3000 and we're trying to get our overall fortunes and let's see what postman performs for us. So once you make this get request, we find all of our fortune objects listed through our overall get request. Once you click, send awesome. Our Jason data is returned to us in a nicely indented and colorized output. Great. Now, how about making a poster quest? So it's open a new postman tad and select Post. Let's enter the same your l that we have for our fortunes in point, since that's the same one that we have for our post endpoint and then we also want to make further configuration for this. We're gonna go to the headers field rather the body field and select raw, and then we're going to select Application Slash and Jason, since that's the type of data that we're sending and notice that once we select Jason slash applications last Jason in her headers field, we automatically get content type and application slash Jason, Great. And now we can enter some Jason data within the body part of this section over here. So let's go ahead and make an overall curly brace. Let's make a new fortunes data. So we're gonna have a message key. And how about our message is success awaits you, awaits you, and then we're gonna need a lucky number now and then. This is 15 and then we're gonna have a spirit animal as well. And how about giraffe? Great. Let's send the request with that big send button now. And as we do so we get the response. And if we scroll down, we see that all the way at the bottom. We see our new object loaded in as well. Awesome. Now we had this postman tools at her disposal. So we have a quicker way than making curl quest to make our custom post and other non get requests. Now this last part of the lesson is optional. We won't be adding new behavior, but exploring a neat feature about note you might be wondering if you're posting this data to this fortunes. Object Lord, Get method now automatically get the new rate of fortunes. Let's use postman to make that get method. So as we do so they're at the bottom. We get our most recent data. Does that seem strange that were getting our most recently posted fortune from the Post Request? After all, if you look at her code well, we require our fortunes data at the beginning of the file, and then our get method is responding with that fortunes data in the Jason format. Shouldn't that Onley ever contain the initial array of fortunes since it required it at the beginning? Well, that's a great three, but let's explore how note is Spartan up to update this global or rate of fortunes, even though we're not explicitly saying fortunes equals something else by changing it their postcode. First off, it might be tempting to think that the candy cat function modifies the fortunes are right. But the JavaScript cat function returns. An entirely new array of data stored within this new fortunes object. Now, so again, it doesnt modify the original array. And then the question becomes, How is it that our global array of fortunes gets updated? Still, the answer lies in the fact that when we write to the fortunes dot Jason file over here notice smart enough to restart our application over here, since one of the acquired modules has changed, which in this case is our fortunes dot Jason module over here from data slash fortunes. Let's prove this by making a confidante log before requiring our fortunes data for the displays, a message that we're requiring that fortunes data. So we're gonna make a constant log that says, requiring fortunes, data and as we do so on a save notice that we're getting listening on Port 3000 and requiring fortune Zita. So now back in Postman, let's remake our post request. So in the post tab, go ahead and just re click that send button. We should get a seven fortune now that looks just like the 61 and not in our development server noticed that the whole server restarted again. We're getting requiring fortunes data and that we're listening on Port 3000 Nice. So in effect, we have restarted the whole back end node server application because we've written to one of our modules. Or rather, one of our modules was updated as a file. So it's to get rid of this confidante love. Now we don't need it. And now we've shown that how running to a module rear start our actual application, which is convenient when we're requiring on global models. They depend on that and you have functions still using that. So with that, let's move on and add some final AP I methods to this fortunes a P I. 19. Update Fortunes Put Method: Let's give our A P I users the ability to edit fortune objects, meaning if they want to change before sends message, Lucky number and or spirit animal will have a specific method to do so. To make this method will use another type of http requests Method called Put put is this English from Post Post is used to create new objects while put is used to update and replace existing ones. All right, let's think about how this put method will be designed. Are put. Method will look like a combination of our get method based on the I. D sub route and the post method that we have in our post. So we'll be able to get the specific fortune to update through its i. D. On the request parameters through a necid route parameter. And then we'll find out how to update its data. Using the past values in the request body as such will create a put method on our express application with the i D. As a parameter on top of the fortunes, Rap will also provide our usual express callback function with the request and response object. Sit back in our code. Let's make a new function called Apt Output. Then we'll provide a shrink with a nested parameter route of I D. Then we'll provide a callback function with a request and response object. They were going to grab our I D from the request Parents object. So let's get the I d. By using destructions in tax, we'll make a look copy of I D. We'll get the one that's going to be stored in our request dot parents, and then we'll also grab the message Lucky number and spirit animal tease from a request body and declared them as look constants by using the structuring syntax as well. So let's get the message, the lucky number and the spirit animal from the body that is within our request. Great. Another. We have our i d from the fortune through the request Haram's as well as our body values to update from the request body. Let's use that data to modify our fortunes. Ap I data. First up, let's find our fortune to update through its i d. By using the job script find function. So we're gonna say our old fortune is a fortune's not find, and then we find it. But looking through every single I d and then passing the one that matches our conditions that the F that represents an individual fortune that we're finding over, it's i d matches the idea that we're getting through a request for EMS, and again we're using double equals. In this case since the i D that's passed through request. France is a shrinking, but the idea is that we have within our fortunes are numbers, so we don't want to make extra type Check with a triple equals. We just want a normal check without the type check. Great. Now that we have our old fortune to repeat, this old fortune is now a reference to our original fortune object because find returns a reference, not the original one. Now, since it's a reference, this basically represents the original object in data, meaning we can edit its keys to have new values and had that become the new data in the original array. So let's update the fortunes message and replace it with a new one that we're getting from the request body. It's under old fortune. We're gonna look at the message and updated to our local message variable. Likewise, for the lucky number, we'll update it to our local lucky number. And finally, for the spirit animal update the spirit animal to the local one. Great. Now we know from our previous post method that we can update our actual fortunes dot Jason file to update our overall fortunes data and the global variable. So we're gonna take a similar approach of writing to our file at the data location, going to fortunes dot Jason, and then we're gonna send a string ified version off our new fortunes object. And again, we can use fortunes this time since over here were updating the original reference to the original data. So we don't have a store in something like new fortunes over here. And then here we provide our callback function as usual in case we get an air. So let's save that. And with this down, we're almost ready to test the method in Postman. We just have to send back our new data which will be stored within the fortunes object. Okay, with this, we're ready to test the method in Postman. So let's go ahead and open a postman. Let's open a new tab within it this time will select the put method again. We'll be adding some body with through raw data. Then let's get the fortunes and point within our post. But this time, let's update Fortune number four over here. Let's give it a new message. And then again, we want to select Jason Applications last Jason. And then we want our message over here. How about love will come soon. How hopeful, then the lucky number. What about 11 and then the spirit animal this time? Shelvey Zebra. So how about zebra? And you could put any values that you want. So with his down, make sure that you have a number for the nesting ground parameter that you selected Jason. Application slash Jason, as one of your body would should make a header of constant tight application. Jason automatically. So with that, let's go ahead and click send, and as we do so we get a response in our data. And look that number four or rather I d for his level come soon. The lucky number is 11 and zebra cool our object updates with his new put method. Now what if we only send partial data? So let's try removing our spirit animal. And how about updating the lucky number to you? 16? Let's see if the message, or rather, just a lucky number updates. But what happens to the spirit animal on number four and the spirit animal in our object data completely disappears. This is because since Spirit Animal doesn't exist within a put request body, it's now going to be undefined in our local method over here. Now, luckily, we can achieve partial updating by using if statements in front of these updates, meaning we can put a guard against updating that data to an undefined piece of data if it's not originally defined. So we'll say if Onley. If there is a message, let's update the message. Likewise, Onley. If there is a lucky number, we're going to update the lucky number. And finally, only if there is a spirit animal. We're going to make that spirit animal update. Now, as we save this, let's retry this once more. We'll give it back its spirit animal of zebra. So that way it has some spirit animal data to work with. So let's send this. The put should update the 4th 1 and again has spirit animal. But what if now we update the lucky number? Will the lucky number changed Too undefined. So let's send this check the response. And now, this time, even though lucky number of wasn't sent, it does not update. And there we have it, only partially updating our fields. Great. Now we have the ability to partially update fields for a P I. Now, before we move on, there's some code improvements we can make notice that we're making the exact same right file twice. Help us out. We can make a helper function in this Abdel Js file that takes care of writing to the fortunes. Jason, let's call it right. Fortunes will do it above our post method over here, so we'll call it Const. Right fortunes, and then we'll set it equal to arrow function. And then, for the actual function, will call the whole fs dot right file method replacing the data with our Jason parameter that we're gonna add over here so we'll give it a Jason Parameter, which represents Jason. That we're now is sending was take this whole fs dot right file and stick it in within. Right fortunes probably want to spell right fortunes correctly as well. And rather than signifying, new fortunes were going to string. If I are Jason and not the end of this since we deleted our efforts dot right file call well, we have to replace it with our helper function. And this time we're passing in our new fortunes data and likewise, over here. We don't have to write this extended call since we have a helper method was right the fortunes and then send in our fortunes data. As you say this. There are development serve updates. Now we should be able to still send this and have it rewrite. And then on a get method, we will be able to get all of our data still with the updated fortunes, let's go ahead and post a new one to make sure the post still works correctly. Indeed, we got another eighth fortune over here. If you make a get request, we know that it writes the file. Since we see eight now, excellent. Now there's one more change we can make now, the code defecation that we have from lines 49 to 51 on updating the old fields on her old fortune isn't so bad since there's only three lines, however. Imagine if we had to do this for, let's say, 4 to 5 or even 10 different fields. Well, we could optimize this by making an array of our teas so speaking array of Archies, which is message lucky number and spirit animal. And then we run a for each function on each of those. And then we'll look at each key individually and then we'll check. Well, we'll check of this key is now present within our request body just like this. If message of here So we'll say if the request that body contains this key, then we're going to update our old fortune. With that T and ST, it's going to be set equal to the request body of accessing that tea over there. So now with that, we can take out these statements over here, and actually, we don't even need to access the local variables from our request body anymore. And as we say this, we have now more concise version that is more powerful. So we simply need to add a new key over here in order to update a new field. If we update our A p I. So it's going check out in Post Mint if our function for the put method still works. So how about deleting spirit? Animal will give it a new lucky number, though, so we should see that our lucky number is updated to something like 19 but zebra isn't updated. City goto i d. Four Yep, the Spirit Animal Zebra wasn't updated, but we still have our lucky number of 19. Awesome. We fully added an updating capability with a put method in our fortunes. A p I. Let's move on and add the last feature to this AP I server. 20. Delete Fortunes Method: for our last piece of functionality will give the A P I user the ability to delete individual fortunes from a p I to allow the user to specify a specific fortune to delete. We use the same strategy as our get by i d and put update methods. We'll have an i d. Parameter upon the request which will use to specify the i d that we would like to remove from our baby. I to make this delete http request we use it elite method from Express. We'll have the similar fortunes and I d end point with the request and response call back. So after put, we'll have our new delete method. It'll be on the fortunes and point name space and then we'll look at the I. D. S a rod parameter. And here's our wreck and raise callback function that fires when we hit this endpoint. Now that we have this, I d. Let's think about how will delete the object from our ray. A good option is to use the filter method on JavaScript, a race the filter method will return a new array based on the condition that we place on each item so we can look at each item in our fortunes Marais and on Lee return items that past a certain condition based on their i d. In our case, it's only return I ds that don't match are requested. Request parameter i d. So first off we're gonna grab our new i d from the wreck dot grams object on the request. A normal saying we're gonna have a new fortunes object now, which allows us to filter down the original fortunes object. We're gonna look at each fortune object individually with f parameter Look at each of those F item objects that represents a fortunes. We're gonna look at their i d and then we're gonna say Onley, give us new fortunes for those that don't match of the I. D. We specified with our request parameters. Great. This will create an entirely new array of Onley items who don't match our request Perimeter I d. Likewise, if it matches the i d, the filter method will decide not to place it in the new fortunes array. Now that we have this new array of data, that's right. The fortunes to our fortunes dot Jason foul using our nice helper method. So we're gonna write these fortunes and passing our new fortunes as a Jason for our right fortunes. Method finally will respond as new fortunes with a response of Jason. So let's just out this functionality in Postman. First, we're gonna make a get request to see what data that we actually have to go ahead and send it Now, once you have it there, go ahead and look through it. I noticed that. Well, we can delete any one of these. But how about one that is duplicate? How about deleting I d number seven? So it's grad something like this. Our whole put endpoint in the open in New Tab. Then we'll specify a delete request. Little pacing our euro. And then again, we're going to want to change the one by idea of eight. So let's change. That's a parameter to eight. All right, so once we have that, we actually don't need to specify any body configuration. It's very much like a get request where we just send it and boom, Here we go. Let's check and then let's look at our response now scrolling down a little bit. It has i d six in i d seven, but it doesn't have I. D. A great How about do leading number five or rather I d five or rather, six. That one's a duplicate. So delete I d six or whatever ones that you have. You may have different data available to you, and there it goes from 5 to 7. Awesome. So we can't find our object and it's deleted. And if we make a get request, our original one in the get request parameter Tad of Postman was Click send. And there we have our updated array with our objects deleted. Awesome object deleted with the idea of six and eight and a fortunes are Ray has filtered it down. With that, we've completed our fortunes ap I with the ability to grab the whole array of fortunes, get them by d, get random one post a new fortune updated fortune and now entirely delete one