Recording

Any website has two parts: a frontend and a backend. The backend handles our logic and data storage and communciates via URLs, but instead of sending web pages, it only sends data.

Now, let’s create something simple with Express to show a basic backend service in action.

console.log("Hello express");

Motivation

Hackers and Painters - A bit old, but perhaps my favorite essay of all time on the nature of CS and how we work. This essay portrays computer science as creative work rather than the typical connection to applied math, science or engineering. It’s a long essay but definitely worth revisiting every few months. Also, it was written by one of the most iconic people in the tech startup space, Paul Graham, who started YCombinator.

Hosted by: Monika Para

Installation

First, make sure that the following are installed on your device. If not, install them:

  • NodeJS. Check to see if you have the latest version installed on your device by typing node -v in your terminal.
  • Postman This will help us visualize the API requests we make. Make an account using either your UIUC Login or the email you used to make your Github account.

Setting Up Your Project

First, we create a folder for the project

$ mkdir express-api
$ cd express-api

Then we use npm to set up the initial boilerplate of the project.

$ npm init

After this, we set up expressJS. This is the framework that actually allows us to make a simple backend by just passing a few functions around.

$ npm install --save express
$ npm install express body-parser morgan``

Make sure to create a .gitignore file with the following content:

node_modules

This prevents us from pushing all our library code to git, which makes our project size much smaller.

Making Your First Express Server

First we import express and create our web server.

// Creating a web server in express
var express = require("express");
var app = express(); 
// runs express server by running 'node app.js' on terminal
app.listen(3000, () => {
    console.log("Server running on http://localhost:3000");
});

Once you have the following code in your app.js file, run node app.js and you should get a message on your terminal saying Server running on http://localhost:3000. Navigate to that URL, and you have made your first Express server - congratulations!

But if you try this, you’ll get an error saying your API has no requests set up. To fix that, let’s create our first API action:

// homepage GET request
app.get("/", (req, res) => {
    res.send("Hello, Express!"); 
});

Now if you rerun it and go to http://localhost:3000, it should say Hello, Express!. Yay! Now the setup is done and the fun part begins.

Understanding CRUD

CRUD is probably one of the most important concepts in backend development. This acronym refers to the 4 broad actions we do with any web backend. Let’s consider this with Reddit, but you’ll quickly realize that these can apply to any site.

  • Create - Create new data. For example: creating a Reddit post.
  • Read - Look up existing data. For example: looking at a post.
  • Update - Update data that already exists. For example: adding an edit to fix a typo.
  • Delete - Remove existing data. For example: removing a post.

Making Your First GET Request

Include the following code before running your server

const bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
  // initialize array of things that make you happy
  const happyArr = [{
    id: 1,
    title: 'suzie sheep'
  },
  {
    id: 2,
    title: 'peppa pig'
  },
  {
    id: 3,
    title: 'boba'}
  ];
  // GET request for values that make you happy 
  app.get('/happiness', function(req, res) {
    return res.send(happyArr);
  });

This code allows you to create a simple JSON object containing things that make you happy. Now, when we navigate to the /happiness URL on our Express server, we’ll see the results of our GET request. Now that you have made your own JSON object and URL, you can navigate to http://localhost:3000/happiness and check it out!

GET Request by ID

The following code snippet creates a GET request so that you can access items in the happyArr by ID:

  // GET request for happy item by id
  app.get('/happiness/:id', (req, res) => {
  const happy = happyArr.find(g => g.id === parseInt(req.params.id));
  if (!happy) {
    return res.status(404).send('The value with the given ID was not found :(');
  }
  res.send(happy);
  });

If you navigate to http://localhost:3000/happiness/1 in your browser, you should be able to see { id: 1, title: 'suzie sheep'}. However, if you replace 1 with a 4 in the URL you get an error that the ID has not been found. This just means that we don’t have an item in the array with that ID. How can we add an entry so we don’t get that error? By making a POST request.

POST Request

The following code snippet will allow you add more queries into your JSON Object:

  // POST request to add an item on Postman
  app.post('/happiness', function(req, res) {
      const happy = {
        id: happyArr.length + 1,
        title: req.body.title
      }
    happyArr.push(happy);
    res.send(happy);
  });

However, since this is a POST request, you need to navigate to Postman. Enter your workspace section and include http://localhost:3000/happiness/ as the URL. On the right, you should see a dropdown with different web requests. Click POST, then click Body -> Raw -> JSON in order to create a JSON entry. For our example, we will include Mommy Pig as an entry of what makes us happy, like so:

{
    "id": 4,
    "title": "mommy pig"
}

Hit send, refresh the browser and you should see an entry of Mommy Pig on the server 🐷. If it doesn’t show up, use CTRL + C in your terminal to kill the server and node app.js to reboot it again, since sometimes Express doesn’t always get updates to the server in a timely manner.

DELETE Request

The following code snippet will allow you to delete an entry of your JSON Object:

// DELETE request to delete a field on Postman
  app.delete('/happiness/:id', function(req, res) {
  const happy = happyArr.find(g => g.id === parseInt(req.params.id));
  if (!happy) {
    return res.status(404).send('The value with the given ID was not found, sad');
  }
  const index = happyArr.indexOf(happy);
  happyArr.splice(index, 1);
  res.send(happy);
});

Just like our POST Request, we want to be able to delete an entry through Postman. The process is the same, except you have to navigate to the specific ID you created to delete the entry on Postman. So say you wanted to delete Mommy Pig, you would have to go to http://localhost:3000/happiness/4 to delete her.

PUT Requests

PUT requests allow you to update an entry to your object. For this tutorial, we won’t cover how to edit existing objects as you would often need to use some sort of database or middleware to handle such a request. We recommend you learn how to use MongoDB with your Express App or learn about JOI to include in your project if you want to work further with PUT requests.

Seeing Your Requests on Postman

Insert your target URL on Postman.

This tutorial will help you navigate through Postman with managing your requests. This is good for trying things out and developing iteratively. You can even create automated tests for your API through Postman.

Learn more

Ethics

International Community of Open Source

FOSS (Free and Open Source Software) initially started in the West Coast of the US, but grew to encompass projects and contributors from all over the world. A lot of the commercial software out there today is still mostly limited to a narrow set of countries, but open source software doesn’t have to deal with immigration restrictions. Entire communities of software developers from Africa, South America, East Asia, Eastern Europe and more are able to contribute to open source software, making it a very global concept. Many countries are even starting to make laws to boost open source contribution. Check out some of the contribution data here.

Ideas

  • Could you build an API to return information about some dataset or service?

  • How can you combine this with a database like PostgreSQL/Mongo DB?

Requirements

  • You should show it off in your README.md file, with animations/video and an explanation of the backend. Make sure to include installation instructions.

  • Has to use a Open Source license via a LICENSE file.

Contributors: Harsh, Maaheen, Monika