REST API with Express.js
Frontend and Backend

A REST API is a backend application. In programming, the terms frontend and backend refer to different parts of a software application, each handling specific responsibilities.

Frontend:

  • The frontend is the user interface, or client-side, of the application that users interact with.
  • It includes everything users see and interact with, such as buttons, forms, and other UI elements.
  • Common frontend technologies include HTML, CSS, and JavaScript, along with frameworks like React, Angular, and Vue.js.

Backend:

  • The backend is the server-side of the application, responsible for data management, business logic, and communication with the database.
  • It handles tasks such as database operations, authentication, and API endpoints.
  • Common backend technologies include programming languages like Python, Java, and Ruby, as well as frameworks like Node.js, Django, and Spring Boot.
  • Databases such as MySQL, PostgreSQL, and MongoDB are often used to store and manage data.

In summary, the frontend is responsible for the user experience, while the backend manages behind-the-scenes processes that enable functionality and data interaction.

Full-Stack Development:

A full-stack developer works with both the frontend and backend, bridging the gap between the user interface and server-side operations. Full-stack development involves using a combination of frontend and backend technologies to build complete applications.

Client-Side vs. Server-Side

In web development, programming languages can be classified as client-side or server-side. This classification refers to where the code is executed: on the client (the user's device) or the server.

Client-Side:

  • Code executed in the user's web browser
  • Examples: JavaScript, HTML, CSS
  • The source code is sent to the browser and executed there
  • Users can view the source code

Server-Side:

  • Code executed on the web server
  • Examples: PHP, Python, Java, Node.js
  • Only the output (usually HTML) is sent to the browser
  • Source code remains hidden from users

JavaScript was traditionally a client-side language executed in web browsers. However, with the introduction of Node.js, it can also be executed on the server.

REST API

REST is acronym for REpresentational State Transfer. REST API is an application which communicates with the clients using HTTP-protocol. The client can be a web-application, or Mobile application or any application which is able to use HTTP. The REST API will handle the connection to the database.

The main HTTP methods used in REST APIs are:

  • GET - Retrieve/read data from the server
  • POST - Create new resources
  • PUT - Replace/update an entire resource
  • PATCH - Partially update a resource
  • DELETE - Remove a resource

Example REST API Structure:

For a user management system, typical endpoints might look like:

  • GET /api/users - Get all users
  • GET /api/users/:id - Get a specific user by ID
  • POST /api/users - Create a new user
  • PUT /api/users/:id - Update an entire user record
  • PATCH /api/users/:id - Update specific fields of a user
  • DELETE /api/users/:id - Delete a user

You can create the REST API using various languages such as Java, PHP, Node.js, Python, etc. This tutorial uses Node.js with the Express framework.

REST allows different messaging formats, such as HTML, JSON, and XML. This tutorial is focused on JSON (JavaScript Object Notation).

REST API uses HTTP requests to GET, PUT, POST and DELETE data.
You can read more about it from:

CRUD operations

Within computer programming, the acronym CRUD stands for create, read, update and delete. The acronym CRUD refers to the major operations which are implemented by databases. Each letter in the acronym can be mapped to a standard Structured Query Language (SQL) statement and HTTP method used in REST APIs.

CRUD Operation SQL Statement HTTP Method REST API Example
Create INSERT POST POST /api/users
Read SELECT GET GET /api/users or GET /api/users/5
Update UPDATE PUT / PATCH PUT /api/users/5 or PATCH /api/users/5
Delete DELETE DELETE DELETE /api/users/5

Note: This mapping shows how database operations (CRUD) are exposed through a REST API using HTTP methods. When a client sends an HTTP request (e.g., POST /api/users), the REST API server translates this into the corresponding SQL operation (INSERT) to interact with the database.

HTTP

HTTP(Hypertext Transfer Protocol) is a protocol which is used to transfer files over the ip-network. You can read more about http from https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview.

HTTP messages

HTTP message is the data that is exchanged between a server and a client. There are two types of messages:

  1. requests: sent by the client to trigger an action on the server
  2. responses: the answer from the server to the client

Http message includes always headers and it can also include a body.

REST API image

You can find a list of http headers from https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers.

HTTP methods

In REST API we can use these HTTP methods:

  • POST (to add data)
  • GET (to show data)
  • PUT (to update data)
  • PATCH (to partially update data)
  • DELETE (to remove data)

When you are using GET and DELETE you can add data only inside the URL or headers. When you are using POST, PUT and PATCH you can add data to both headers and body.

Example if you want to send a variable named fname, with a value Jim using GET-method, then the url will be something like
http://localhost/api/?fname=Jim
But if you are using POST-method then, the url is just like this
http://localhost/api

When we are using DELETE, we will add the id to the url on the same way as in GET-method. And when we are using PUT or PATCH, we will add the id to the url and the update data to the body.

A common practice when building a REST API is that you don't need to include variable names as query parameters in your GET requests. So that instead of this kind of url
http://localhost/api/?id=5
You can use a cleaner, more RESTful URL like:
http://localhost/api/5

PUT vs PATCH

Both PUT and PATCH methods are used to update existing resources, but they have different semantic meanings:

PUT is typically used for full resource update. When you send a PUT request, you should send the complete representation of the resource. If you omit some fields, they might be set to null or default values.

PATCH is used for partial resource update. When you send a PATCH request, you only need to send the fields that you want to modify. The other fields remain unchanged.

Example:
Let's say you have a user resource with fields: name, email, phone, and address.

  • With PUT, if you want to update only the email, you typically need to send all fields: name, email, phone, and address.
  • With PATCH, you can send only the email field, and the other fields remain unchanged.

Important note: However, the actual behavior depends on how the developer implements the backend code. The HTTP method itself doesn't enforce these rules - it's the SQL code and business logic written by the developer that determines whether the update is full or partial. A developer could implement PUT to do partial updates or PATCH to do full updates, but this would go against REST conventions and best practices.

You can read more about those methods from:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
http://www.restapitutorial.com/lessons/httpmethods.html

HTTP status codes

The http response includes status code, which gives information about the response. The most important classes of the codes are:

  • 200 - 299 : Success
  • 400 - 499 : Client errors
  • 500 - 599 : Server error

You can read about the status codes from:
https://www.restapitutorial.com/httpstatuscodes.html

HTTPS

HTTPS(Hypertext Transfer Protocol Secure) is an extension for the HTTP. If you use HTTP, all the information will be transfered in plain text format. But if you use HTTPS, the information will be encrypted.

JSON
JSON Objects

JSON objects are written inside curly brackets. Example like this

{
	"id_book": 11,
	"name": "javascript",
	"author": "Mike Jones",
	"isbn": "9780030604577"
}

JSON Arrays

JSON arrays are written inside square brackets. The array can contain several objects. Like this

[
	{
		"id_book": 11,
		"name": "New Book",
		"author": "Mike",
		"isbn": "22"
	},
	{
		"id_book": 7,
		"name": "Signal Slot",
		"author": "Jim Bim",
		"isbn": "2345-66"
	}
]

CORS

CORS allows web applications from one domain to access resources from another domain. Without CORS, browsers restrict cross-origin HTTP requests initiated by scripts, which could prevent your API from being accessed by clients running on different domains.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Authentication/Authorization

Authentication and authorization are two vital information security processes that administrators use to protect systems and information. Authentication verifies the identity of a user or service, and authorization determines their access rights.

Authentication

The purpose of authentication is to verify that someone or something is who or what they claim to be.

Authorization

Authorization is the security process that determines a user or service's level of access. In technology, we use authorization to give users or services permission to access some data or perform a particular action.

HTTP Basic authentication

In the context of an HTTP transaction, basic access authentication is a method for an HTTP user agent (e.g. a web browser) to provide a username and password when making a request. In basic HTTP authentication, a request contains a header field in the form of Authorization: Basic <credentials>, where credentials is the Base64 encoding of ID and password joined by a single colon.

⚠️ Security Warning:

HTTP Basic authentication has significant security limitations:

  • Credentials sent with every request: Username and password are transmitted in every HTTP request
  • Base64 is NOT encryption: Base64 encoding can be easily decoded (similar to JWT payload)
  • Requires HTTPS: Without HTTPS, credentials are sent in plain text over the network
  • No logout mechanism: Browser caches credentials until the session ends
  • No expiration: Credentials remain valid indefinitely unless changed

Recommendation: HTTP Basic authentication should only be used for:

  • Internal tools and development environments
  • Simple prototypes and testing
  • Always combined with HTTPS in any real-world scenario

✓ For production applications: Use JWT authentication or OAuth2 instead, which provide better security, token expiration, and stateless authentication.

JSON Web Token (JWT) authentication

JWTs or JSON Web Tokens are most commonly used to identify an authenticated user. JWT authentication follows a 4 step process:

  1. Client sends credentials: Client sends POST request with username and password to auth server.
  2. Server validates and generates token: Server checks the credentials against the database. If valid, server generates a JWT token and sends it to the client. The server does not store the token - the client saves it (typically in localStorage or sessionStorage).
  3. Client sends authenticated request: For every subsequent request, the client sends the JWT in the Authorization header (Bearer scheme). Server validates the token using the secret key.
  4. Server responds with data: Once the token is validated, server sends the requested data to the client.

JWT Authentication Process

Step 1: Client sends credentials → Server checks database
Step 2: Database validates → Server generates JWT token
Step 3: Client sends request with JWT in header
Step 4: Server validates token and sends data
👤
Client
Web/Mobile App
🔐
Auth Server
Backend API
🗄️
Database
User Data
POST: username + password
Query user
User valid ✓
JWT Token
Request + JWT in Header
Protected Data
HTTP Request with Webtoken

When sending an authenticated request, the JWT token is included in the Authorization header using the Bearer scheme:

HTTP Request Headers:
GET /api/users/profile HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Format: Authorization: Bearer <token>

JWT Token Structure:
A JWT token consists of three parts separated by dots (.):

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMywibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
1. Header (Algorithm & Token Type)
{
  "alg": "HS256",
  "typ": "JWT"
}
2. Payload (Data/Claims)
{
  "userId": 123,
  "name": "John Doe",
  "iat": 1616239022
}
3. Signature (Verification)
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)
⚠️ Important:
  • Not encrypted: The Header and Payload are only Base64-encoded, not encrypted. Anyone can decode and read them.
  • Don't store sensitive data: Never put passwords, credit card numbers, or other sensitive information in the token payload.
  • Signature provides integrity: The signature ensures the token hasn't been tampered with, but doesn't hide the content.
  • Use HTTPS: Always transmit JWT tokens over HTTPS to prevent interception.

Example of sending JWT token in JavaScript:

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

fetch('/api/users/profile', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  }
})
.then(response => response.json())
.then(data => console.log(data));



Toggle Menu