The Basics : Backend Development [Part 1/2]
Tags: webdev, mern, backend, programming
Published: 2023-07-07 07:18:02

This article will include all the major terms you hear when backend development is discussed. You can use this to skim through all the important concepts before an interview ;) 
Note that this article is written with the MERN stack in view, but the underlying concepts are universal.

## Table of Contents 

- [Introduction](#itb)
- [HTTP](#http)
- [Middleware Functions](#middleware)
- [REST Architecture](#rest)
- [CRUD Operations](#crud)
- [MVC Architecture](#mvc)
- [CORS](#cors)
- [Frameworks](#frameworks)

<h2 id="itb">1. Introduction to Backend</h2>
The back-end is the code that runs on the server, that receives requests from the clients, and contains the logic to send the appropriate data back to the client. The back-end also includes the database, which will persistently store all of the data for the application.

The backend is made up of three parts :

- **The server** : This is the computer that receives requests. To make your machine a server, install Node.js which is runtime environment for Javascript and listen on desired port number.

<br>

- **The app** : This is the application running on the server that listens for requests, retrieves information from the database, and sends a response. A framework like express helps in making these apps.

<br>

- **The database** : Databases are used to organize and persist data. They can be classified into SQL and NoSQL databases. MERN stack follows MongoDB database which is a NoSQL database.

<h2 id="http">2. HTTP</h2>
HTTP stands for _Hypertext Transfer Protocol_  and is used to structure requests and responses over the internet. HTTP requires data to be transferred from one point to another over the network. The resources itself are transferred with the help of a TCP connection.

### Analogy

> Suppose you are at restaurant and you call a waiter for him to take your order. You dictate your order in english and the waiter notes it down, he then makes a track (at the speed of light) to the kitchen and tells the chef to prepare the order. He comes back, while ripping of the track, with the dish or some unfortunate news that the dish can’t be prepared.

![HTTP with analogy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/209pwfb6l6j4i8csq5fr.png)

Here, you are the _client_, the waiter the _server_ and the chef is the _database_. To dictate your order you chose english, while the request on web uses _HTTP_, the track is the _TCP connection_ to deliver resources, and whatever the waiter comes back with is the _response_. The dish you want to eat is the _URL_ (uniform resource locator), this tells the server what actually the client needs.
 
### How it is different from HTTPS ?

This ‘S’ in HTTPS stands for _security_. Coming to the analogy above, if you tell the waiter to include a secret sauce in the dish, it might not be a good idea for the waiter to note it in plain text, ( it can be read by anyone at the track junctions !) To secure sensitive and personal content, some servers may provide an encryption facility.

<h2 id="middleware">3. Middleware Functions</h2>
Middleware is any code that executes between the server receiving a request and sending a response. These functions might modify the request object, query the database, or otherwise process the incoming request.

In the analogy, the actual preparation of the dish can be thought of a middleware. Middleware functions typically end by passing control to the next (using next()) middleware function, rather than by sending a response. You often see them recieve three parameters — req, res and next.

```javascript
const express = require('express')
const app = express()

//our middleware functions
const myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(3000)
// code excerpt taken from express documentation

//Output
/* Every time the app receives a request, 
it prints the message “LOGGED” to the terminal.*/
```

<h2 id="rest">4. REST Architecture</h2>
REST, or _REpresentational State Transfer_, is an architectural style for building API’s , providing standards between computer systems on the web, making it easier for systems to communicate with each other.

A RESTful API uses commands to obtain resources. In REST, each resource is identified by a unique URI (Uniform Resource Identifier) and can be manipulated using standard HTTP methods such as:

- **GET** to retrieve a resource;
- **PUT** to change the state of or update a resource, which can be an object, file or block;
- **POST** to create that resource; and
- **DELETE** to remove it.


![REST api for movie app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qr93nb9kuwtt59nb6arc.png)


It is based on the idea that the REST APIs are **stateless**, meaning that calls can be made independently of one another, and each call contains all of the data necessary to complete itself successfully.

It also **separates the concern** of server and client, allowing their implementation to be done independently of each other.

> By using a REST interface, different clients hit the same REST endpoints, perform the same actions, and receive the same responses.

<h2 id="crud">5. CRUD Operations</h2>
CRUD stands for **Create, Read, Update and Delete** operations. Think of a simple blog website, the basic function you want to give your users are — creating a blog, reading blogs of other people, updating content and deleting a blog. It’s crucial for a developer to know and implement these CRUD operations.

Corresponding to each type of operation there is a different HTTP verb that is included in the request that the client makes. HTTP verbs for CRUD are POST, GET, PUT, and DELETE respectively. Apart from HTTP verbs, a client’s request have certain other fields like — header and accept parameter, a path to resource and optional body content. Read about it here.

Similarly, server’s response consists of — content type, status code and any data the client requested for (read operation). Client will only accept the data if it’s type is one of the mentioned types in header of the request.

Example

```
//Clients request :
GET http://fashionboutique.com/customers
Accept: application/json
/*
HTTP verb : GET
Resource Locator : fashionboutique.com/customers
Accept files which are application/json format.
*/
```

```
//Servers response
Status Code: 200 (OK)
Content-type: application/json
/*
Status code 200 implies that response is successfully generated. 
Content type : the response is in application/json format
followed by the actual customers data
*/
```

<h2 id="mvc">6. MVC Architecture</h2>
MVC stands for Model, View, Controller and refers to the architecture of your code. It is a way to organize your application by separating all of the actions into 3 main components: Models, Views and Controllers.


![Model View Controller diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9taa6aja0tf3mwx4hqdz.png)

- **Models** are the basic building blocks of your database. So for every entry in your DB , you’ll create a model that holds the details of that entry. Models define the types of information that get used by your views and controllers. (Mongoose)

<br>

- **Views** are the component that generates the UI for your application. It uses data supplied by a controller, plug that data in html with the help of a templating engine and display the desired information.(EJS or React-engine).

<br>

- **Controllers** are the components that decide what view to display and what information is going to be put into it. It’s where the main logic of your server resides.

<h2 id="cors">7. CORS</h2>
The Same Origin Policy is an important security measure that basically says “Only requests from the same origin (the same IP address or URL) should be allowed to access this API”.

But, we are specifically trying to set up our API so that we can access it from different origins, so to enable that we need to set up _Cross-origin resource sharing_, or CORS.

Setting up CORS is very easy by using a npm library of the same name.

```javascript
//Simple Usage (Enable All CORS Requests)
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
```

<h2 id="frameworks">8. Frameworks</h2>
A framework is just boilerplate code bundled in an organised way. A obvious advantage of using a framework is that you don’t have to repeatedly write the same code. Another is that it gives you the organisation of files from the start according to MVC principles. Some good examples are —

- Express
- Django,
- Ember
- Rails and many more.

Using frameworks can reduce the verbose and provide necessary abstraction to speed up your development .

> Check out the ‘Part 2' of this primer to know about how to scale and optimise your application and other cool stuff.

---


References :

- https://www.codecademy.com/article/back-end-architecture
- https://www.codecademy.com/article/http-requests
- https://www.codecademy.com/article/what-is-rest
- https://www.theodinproject.com/lessons/nodejs-express-102-crud-and-mvc
- https://www.theodinproject.com/lessons/nodejs-api-basics
- https://expressjs.com/en/resources/middleware/cors.html

Image Source :
- Cover : https://realpython.com/tutorials/front-end/
- HTTP : https://apipheny.io/wp-content/uploads/2020/10/api-waiter-1.png
- REST : https://www.sitepoint.com/creating-restful-apis-express-4/#creating-the-api-for-the-movie-app
- MVC : https://www.interviewbit.com/blog/mvc-architecture/