What is a REST API and How to create one with JavaScript + Bonus

  



In the previous article, we explored what an API (Application Programming Interface) is and how it allows different applications to communicate with each other. In this article, we'll take a deeper look at a specific and widely used type of API: the REST API.

๐Ÿ”— Do you like Techelopment? Check out the website for all the details!

What Does REST Mean?

REST stands for REpresentational State Transfer, an architectural style introduced by Roy Fielding in his PhD dissertation in 2000. It is designed for distributed systems, particularly the web.

A REST API is an interface that allows two systems to communicate over the HTTP protocol while following REST principles.


The 6 Key Principles of a RESTful API

To be considered RESTful, an API must follow these six principles:

  1. Client-Server Architecture
    The client and server must be separated. The client handles the UI, while the server handles logic and data.
  2. Stateless
    Each request from the client must contain all necessary information. The server does not store session state between requests.
  3. Cacheability
    Responses should indicate whether they are cacheable to improve performance.
  4. Uniform Interface
    Resources must be identified by URLs, and standard HTTP methods must be used:
    • GET → retrieve a resource
    • POST → create a new resource
    • PUT → update an existing resource
    • DELETE → delete a resource
  5. Layered System
    The system may consist of multiple layers (proxies, gateways, etc.) without the client being aware.
  6. Code on Demand (optional)
    The server can return executable code (e.g., JavaScript) to the client when needed.

Common Mistakes When Building REST APIs

Building a good RESTful API can be tricky. Here are some of the most common mistakes:

  • Using verbs in the URL – Example: /getUser/1 → better: /users/1 with GET method.
  • Misusing HTTP methods – Always using POST even for reads or deletes breaks REST semantics.
  • Returning incorrect HTTP status codes – Always returning 200 OK even on errors is a bad practice.
  • Lack of documentation – Even the best API is useless without clear and accessible documentation.
  • Breaking statelessness – Storing session state on the server makes scaling harder and breaks REST design.

How to Create a Simple REST API with JavaScript (Node.js + Express)

Requirements

  • Node.js installed
  • Initialize project with npm init -y
  • Install Express:
    npm install express

Basic Code Example

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

let users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];

// GET all users
app.get('/users', (req, res) => {
  res.json(users);
});

// GET user by ID
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (!user) return res.status(404).send('User not found');
  res.json(user);
});

// POST new user
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// DELETE user
app.delete('/users/:id', (req, res) => {
  users = users.filter(u => u.id !== parseInt(req.params.id));
  res.status(204).send();
});

app.listen(port, () => {
  console.log(`API listening at http://localhost:${port}`);
});

Bonus: How to Host Your REST API Online for Free

You can use platforms like Render, Railway, Glitch, or Vercel (with serverless functions). Here's how to deploy with Render (For personal projects and small-scale applications):

  1. Create a GitHub repository with your Node.js code.
  2. Go to https://render.com and sign up.
  3. Click “New” → “Web Service”.
  4. Connect your repo, select “Node.js”, set your start command (e.g., node index.js) and deploy.

In just a few minutes, your API will be publicly available!


How to Call a REST API in JavaScript (and More)

After building a REST API, the next step is learning how to use it—by sending HTTP requests to read, create, or delete data. Here's how to do that using Postman, JavaScript, and cURL.

๐Ÿ”— Base URL

If you're running the API locally:

http://localhost:3000

If it's online (e.g., Render):

https://your-app.onrender.com

๐Ÿ“ฅ 1. Get all users (GET /users)

✅ Postman

  • Method: GET
  • URL: /users

✅ JavaScript

fetch('http://localhost:3000/users')
  .then(res => res.json())
  .then(data => console.log(data));

✅ cURL

curl http://localhost:3000/users

๐Ÿ“ฅ 2. Get a single user (GET /users/:id)

GET /users/1

✅ JavaScript

fetch('http://localhost:3000/users/1')
  .then(res => res.json())
  .then(data => console.log(data));

✅ cURL

curl http://localhost:3000/users/1

➕ 3. Create a new user (POST /users)

✅ Postman

  • Method: POST
  • Headers: Content-Type: application/json
  • Body:
{
  "name": "Charlie"
}

✅ JavaScript

fetch('http://localhost:3000/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Charlie' })
})
  .then(res => res.json())
  .then(data => console.log(data));

✅ cURL

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Charlie"}'

๐Ÿ—‘️ 4. Delete a user (DELETE /users/:id)

✅ JavaScript

fetch('http://localhost:3000/users/2', {
  method: 'DELETE'
})
  .then(res => console.log('User deleted, status:', res.status));

✅ cURL

curl -X DELETE http://localhost:3000/users/2

๐Ÿงช Starting the Local Server

Make sure to start your Node.js server before testing:

node index.js



Conclusion

REST APIs are a powerful and widely adopted standard for building scalable and maintainable web services. Following REST principles isn't just about style—it's a practical way to create intuitive and reliable APIs. With tools like Node.js and Express, building one is easy, and free platforms like Render or Railway let you publish it online in no time.

Remember: 
an API that respects the REST principles is also called a RESTful API



Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment