Logo

dev-resources.site

for different kinds of informations.

Learning REST APIs in JavaScript

Published at
1/7/2025
Categories
javascript
restapi
rest
api
Author
arjun98k
Categories
4 categories in total
javascript
open
restapi
open
rest
open
api
open
Author
8 person written this
arjun98k
open
Learning REST APIs in JavaScript

Learning REST APIs in JavaScript

REST APIs (Representational State Transfer Application Programming Interfaces) are widely used for building networked applications. This article will help you understand how to work with REST APIs in JavaScript, covering both client-side and server-side implementations.


1. What is a REST API?

A REST API allows clients (such as browsers or mobile apps) to communicate with servers to fetch or manipulate data. It follows a stateless architecture using standard HTTP methods.

Core Concepts

  1. Resources: Represented by endpoints (e.g., /users for user data).
  2. HTTP Methods:
    • GET: Retrieve data.
    • POST: Create a new resource.
    • PUT: Update an existing resource.
    • DELETE: Remove a resource.
  3. Data Format: JSON is commonly used to exchange data.
  4. HTTP Status Codes:
    • 200 OK: Success.
    • 201 Created: Resource created.
    • 400 Bad Request: Client-side error.
    • 404 Not Found: Resource not found.
    • 500 Internal Server Error: Server issue.

2. Tools and Setup

  • For Client-Side:

    • Browser (JavaScript with fetch or axios library).
    • Use APIs like https://jsonplaceholder.typicode.com for practice.
  • For Server-Side:

    • Install Node.js and use the Express framework.

3. Working with REST APIs on the Client Side

JavaScript provides the fetch() API and third-party libraries like axios to interact with REST APIs.


Fetching Data Using fetch()

Here’s how to retrieve data from a REST API.

// Fetch data from an API
const fetchUsers = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const users = await response.json(); // Parse JSON data
    console.log(users);
  } catch (error) {
    console.error('Error fetching users:', error);
  }
};

fetchUsers();
Enter fullscreen mode Exit fullscreen mode
Explanation:
  1. fetch(url): Makes an HTTP request.
  2. response.json(): Converts the response to JSON format.
  3. Error handling is implemented using try...catch to catch network errors or invalid responses.

Sending Data with POST

To create a new resource, use the POST method with the fetch() API.

const createUser = async () => {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users', {
      method: 'POST', // HTTP method
      headers: {
        'Content-Type': 'application/json', // Specify JSON format
      },
      body: JSON.stringify({ // Convert JavaScript object to JSON
        name: 'Jane Doe',
        email: '[email protected]',
      }),
    });

    const newUser = await response.json(); // Parse JSON response
    console.log(newUser);
  } catch (error) {
    console.error('Error creating user:', error);
  }
};

createUser();
Enter fullscreen mode Exit fullscreen mode
Key Points:
  • The method option specifies the HTTP method.
  • The headers option is used to indicate the content type.
  • The body contains the JSON payload.

4. Building REST APIs on the Server Side

On the backend, Node.js with the Express framework is commonly used to build REST APIs.

Setting Up Your Environment

  1. Install Node.js: Download Node.js.
  2. Initialize a new project:
   mkdir rest-api-demo
   cd rest-api-demo
   npm init -y
   npm install express
Enter fullscreen mode Exit fullscreen mode

Creating a Simple REST API

Here’s an example of a basic REST API server.

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

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

// Sample data
let users = [
  { id: 1, name: 'Alice', email: '[email protected]' },
  { id: 2, name: 'Bob', email: '[email protected]' },
];

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

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

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

// PUT to update a user
app.put('/users/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  if (user) {
    Object.assign(user, req.body); // Update user properties
    res.json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

// DELETE a user
app.delete('/users/:id', (req, res) => {
  const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
  if (userIndex !== -1) {
    users.splice(userIndex, 1); // Remove user from array
    res.status(204).send(); // No content response
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode
Explanation:
  • Middleware: app.use(express.json()) parses incoming JSON requests.
  • Routes:
    • GET /users: Fetch all users.
    • GET /users/:id: Fetch a specific user.
    • POST /users: Add a new user.
    • PUT /users/:id: Update user details.
    • DELETE /users/:id: Remove a user.

5. Testing Your REST API

You can test your API using tools like Postman or command-line utilities like curl.

Using Postman

  1. Install Postman from here.
  2. Create a new request:
    • GET http://localhost:3000/users: Fetch all users.
    • POST http://localhost:3000/users: Add a user with a JSON body.

Using curl

curl -X GET http://localhost:3000/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' http://localhost:3000/users
Enter fullscreen mode Exit fullscreen mode

6. Best Practices for REST API Development

  1. Use meaningful endpoint names (e.g., /users instead of /data).
  2. Validate user input to prevent invalid or harmful data.
  3. Follow consistent HTTP status codes.
  4. Document your API using tools like Swagger or Postman.

my working code repo
postman img

Conclusion

REST APIs are a cornerstone of modern web development. By learning to interact with REST APIs in JavaScript, both on the client and server sides, you’ll gain a powerful skill set for building and integrating applications. Practice is key—start by consuming public APIs and then build your own API using Node.js and Express.


Feel free to ask questions or seek clarifications on any part of this guide!

rest Article's
30 articles in total
Favicon
Best Practices for Securing REST APIs: Balancing Performance, Usability, and Security
Favicon
Learning REST APIs in JavaScript
Favicon
Validation in Spring REST Framework (SRF)
Favicon
API Design Best Practices in 2025: REST, GraphQL, and gRPC
Favicon
GraphQL vs REST: When to Choose Which for Your Node.js Backend
Favicon
REST VS SOAP
Favicon
Discover the 9 Best Open-Source Alternatives to Postman
Favicon
Building Robust REST Client with Quarkus: A Comprehensive Guide
Favicon
O que é REST API?
Favicon
Building Async APIs in ASP.NET Core - The Right Way
Favicon
Why Clear and Meaningful Status Codes Matter in Your REST API
Favicon
Understanding Request and Response Headers in REST APIs
Favicon
How Scale Changes Everything - The LiveAPI Perspective
Favicon
A Closer Look At API Docs Generated via LiveAPI's AI
Favicon
Quick and Easy: How to Test RESTful APIs in Java
Favicon
Understanding API Architectural Styles: REST, GraphQL, SOAP and More
Favicon
Implementing Pagination, Filtering, and Sorting in REST APIs
Favicon
REST In Peace
Favicon
Understanding HTTP Status Codes
Favicon
Musings Over What Makes LiveAPI Different (from Swagger Et Cetera)
Favicon
Introduction to APIs: Supercharging Your Web Development Journey
Favicon
An Innovative Way to Create REST APIs
Favicon
Best Practices for Developing and Integrating REST APIs into Web Applications
Favicon
Как подружить котиков, слонов и китов: тестирование Spring-приложений с Testcontainers 🐱🐘🐋
Favicon
Implementing Idempotent REST APIs in ASP.NET Core
Favicon
Understanding REST vs. GraphQL: Which One Should You Choose?
Favicon
Problem Details for ASP.NET Core APIs
Favicon
REST vs. GraphQL: Key Differences, Benefits, and Which One to Choose for Your Project
Favicon
REST vs. GraphQL: Choosing the Right API for Your Project
Favicon
Optimizing Your REST Assured Tests: Setting Default Host and Port, GET Requests, and Assertions

Featured ones: