๐Ÿ› ️ How to Create an API from Scratch Using JavaScript

  



APIs (Application Programming Interfaces) are essential for modern web development. Whether you're building a mobile app, a single-page application, or connecting different systems, APIs let you send and receive data easily. In this guide, we’ll walk through all the steps to create a simple RESTful API using JavaScript with Node.js and Express.

By the end of this post, you’ll be able to create a basic API that performs CRUD (Create, Read, Update, Delete) operations — without needing to look for more information elsewhere.

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

๐Ÿ“ฆ Step 1: Set Up Your Project

First, we need to initialize a new Node.js project and install dependencies (here "Getting Started with Node.js" how to install node.js).

Open the terminal (cmd or PowerShell in Windows, shell in Unix like systems) and digit the following commands:
mkdir my-api
cd my-api
npm init -y
npm install express

This will create a new folder, initialize a project, and install Express — the most popular web framework for Node.js.


๐Ÿงฑ Step 2: Create Your Server

// Importing Express
const express = require('express');
const app = express();

// Middleware to parse JSON bodies
app.use(express.json());

// Define a port for the server
const PORT = 3000;

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

✅ Explanation: This code sets up a basic Express server and enables it to handle JSON data.


๐Ÿ—ƒ️ Step 3: Define Some Sample Data

// Sample data - a list of books
let books = [
  { id: 1, title: "The Alchemist", author: "Paulo Coelho" },
  { id: 2, title: "1984", author: "George Orwell" },
];

๐Ÿ” Step 4: Create API Endpoints

๐Ÿ”น GET - Read all books

app.get('/api/books', (req, res) => {
  // Return the full list of books
  res.json(books);
});

๐Ÿ”น GET - Read a single book

app.get('/api/books/:id', (req, res) => {
  const bookId = parseInt(req.params.id); // Convert ID to number
  const book = books.find(b => b.id === bookId);

  if (!book) {
    return res.status(404).json({ message: "Book not found" });
  }

  res.json(book);
});

๐Ÿ”น POST - Create a new book

app.post('/api/books', (req, res) => {
  const { title, author } = req.body;

  // Create a new book object
  const newBook = {
    id: books.length + 1,
    title,
    author
  };

  // Add the new book to the array
  books.push(newBook);

  res.status(201).json(newBook);
});

๐Ÿ”น PUT - Update an existing book

app.put('/api/books/:id', (req, res) => {
  const bookId = parseInt(req.params.id);
  const { title, author } = req.body;

  const book = books.find(b => b.id === bookId);

  if (!book) {
    return res.status(404).json({ message: "Book not found" });
  }

  // Update book properties
  book.title = title || book.title;
  book.author = author || book.author;

  res.json(book);
});

๐Ÿ”น DELETE - Remove a book

app.delete('/api/books/:id', (req, res) => {
  const bookId = parseInt(req.params.id);
  books = books.filter(b => b.id !== bookId);

  res.json({ message: "Book deleted successfully" });
});

✅ Step 5: Test Your API

You can test the API using tools like:

  • Postman (here a guide)
  • curl
  • Or simply using your browser for GET requests (e.g., http://localhost:3000/api/books)

๐Ÿงช Optional: Add CORS Support

If you plan to call this API from a frontend running in the browser (like React or Vue), install and enable CORS (here "What is CORS and How to Manage It" you can find an in-depth analysis on the topic):

npm install cors
const cors = require('cors');
app.use(cors());

๐ŸŽ‰ Conclusion

Now you’ve built a fully functional API using JavaScript, Node.js, and Express! You can extend it further by connecting it to a real database like MongoDB or PostgreSQL, adding authentication, or deploying it online.

This is your foundation — from here, the sky’s the limit ๐Ÿš€



Follow me #techelopment

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