DEV Community

Cover image for Understanding APIs: A Beginner's Guide to Web APIs
Tech Tales
Tech Tales

Posted on

Understanding APIs: A Beginner's Guide to Web APIs

Understanding APIs: A Beginner's Guide to Web APIs

If you're learning web development, you've probably seen code like this:

fetch("/api/users")
Enter fullscreen mode Exit fullscreen mode

But what actually happens when this code runs?

How does a React application communicate with a backend? What is a REST API? What are endpoints, HTTP methods, JSON, status codes, and authentication?

In this guide, we'll break down the fundamentals of APIs and see how they are used in real-world web applications.

What Is an API?

API stands for Application Programming Interface.

Simply put, an API allows different software applications to communicate with each other.

In modern web applications, a frontend usually doesn't communicate directly with a database. Instead, it sends requests to a backend through an API.

A typical flow looks like this:

Frontend
   ↓
API Request
   ↓
Backend Server
   ↓
Database
   ↓
Backend Server
   ↓
API Response
   ↓
Frontend
Enter fullscreen mode Exit fullscreen mode

For example, when you search for restaurants in a food delivery application, the frontend can send a request to a backend API. The backend processes the request, retrieves the required information, and returns a response.

The frontend can then display that information to the user.

Why Do We Use APIs?

Imagine you're building an employee management application.

The application might need to:

  • Get employee details
  • Add a new employee
  • Update employee information
  • Delete employees
  • Search for employees

Instead of allowing the frontend to directly access the database, we can create APIs for these operations.

For example:

GET    /api/employees
POST   /api/employees
PUT    /api/employees/101
DELETE /api/employees/101
Enter fullscreen mode Exit fullscreen mode

This separation provides several benefits:

  • Better separation between frontend and backend
  • Improved security
  • Easier maintenance
  • Reusable backend services
  • Support for multiple clients
  • Easier integration with third-party services

What Is a REST API?

One of the most common approaches to building web APIs is REST.

REST stands for Representational State Transfer.

REST APIs commonly use HTTP methods to perform operations on resources.

For example, suppose employees is a resource.

We might have:

GET     /api/employees
GET     /api/employees/101
POST    /api/employees
PUT     /api/employees/101
DELETE  /api/employees/101
Enter fullscreen mode Exit fullscreen mode

Each HTTP method represents a different operation.

Let's look at them one by one.

HTTP Methods

  1. GET

GET is used to retrieve data.

fetch("/api/employees")
  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

This request asks the server to return employee information.

  1. POST

POST is commonly used to create new data.

fetch("/api/employees", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "John",
    role: "Developer"
  })
});
Enter fullscreen mode Exit fullscreen mode

Here, the frontend sends employee information to the backend.

The backend can validate the data and store it in the database.

  1. PUT

PUT is generally used to update an existing resource.

fetch("/api/employees/101", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "John",
    role: "Senior Developer"
  })
});
Enter fullscreen mode Exit fullscreen mode

This request updates employee 101.

  1. DELETE

DELETE is used to remove a resource.

fetch("/api/employees/101", {
  method: "DELETE"
});
Enter fullscreen mode Exit fullscreen mode

This tells the backend to delete employee 101.

What Is an API Endpoint?

An API endpoint is a specific URL through which a client accesses a resource or functionality.

For example:

GET /api/products
Enter fullscreen mode Exit fullscreen mode

This could return a list of products.

To retrieve a specific product:

GET /api/products/25
Enter fullscreen mode Exit fullscreen mode

A typical endpoint can be understood as:

Base URL + API Path + Resource + Identifier
Enter fullscreen mode Exit fullscreen mode

For example:

https://example.com/api/products/25
Enter fullscreen mode Exit fullscreen mode

Here:

https://example.com → Base URL
/api                 → API path
/products            → Resource
/25                  → Resource ID
Enter fullscreen mode Exit fullscreen mode

API Requests and Responses

API communication involves two important things:

Request → Client sends data to the server

Response → Server sends data back to the client

For example, a client might send:

{
  "name": "John",
  "email": "john@example.com"
}
Enter fullscreen mode Exit fullscreen mode

The backend processes the request and might return:

{
  "success": true,
  "message": "Employee created successfully",
  "employeeId": 101
}
Enter fullscreen mode Exit fullscreen mode

The frontend can then use the response to update the UI.

What Is JSON?

JSON, or JavaScript Object Notation, is one of the most common formats used to exchange data through APIs.

For example:

{
  "id": 101,
  "name": "John",
  "role": "Developer",
  "experience": 3
}
Enter fullscreen mode Exit fullscreen mode

JSON is popular because it is:

  • Easy to read
  • Lightweight
  • Easy to process
  • Supported by many programming languages
  • Commonly used with REST APIs

If you're working with JavaScript, you'll encounter JSON constantly.

HTTP Status Codes

APIs use HTTP status codes to tell the client what happened after processing a request.

Some common status codes are:

Status Code Meaning
200 OK
201 Created
400 Bad Request
401 Unauthorized
404 Not Found
500 Internal Server Error

For example:

200 OK
Enter fullscreen mode Exit fullscreen mode

means the request was successful.

While:

404 Not Found
Enter fullscreen mode Exit fullscreen mode

means the requested resource could not be found.

Understanding these codes is extremely useful when debugging API problems.

API Authentication

Not every API endpoint should be publicly accessible.

For example, an employee management system shouldn't allow anyone to access employee data.

This is where authentication comes in.

Authentication verifies the identity of the person or application making the request.

After login, a backend may generate an authentication token.

The client can then send the token with future requests:

Authorization: Bearer <token>
Enter fullscreen mode Exit fullscreen mode

The backend verifies the token before allowing access to protected resources.

Authentication is commonly used in:

  • Banking applications
  • E-commerce applications
  • Social media applications
  • Admin dashboards
  • Employee management systems
  • Payment applications

Using APIs in React

React applications frequently communicate with APIs.

Here's a simple example:

import { useEffect, useState } from "react";

function Employees() {
  const [employees, setEmployees] = useState([]);

  useEffect(() => {
    fetch("/api/employees")
      .then(response => response.json())
      .then(data => setEmployees(data));
  }, []);

  return (
    <div>
      {employees.map(employee => (
        <p key={employee.id}>{employee.name}</p>
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Let's break down what happens:

  1. React renders the component.
  2. useEffect() runs.
  3. fetch() sends an API request.
  4. The server returns employee data.
  5. setEmployees() stores the response.
  6. React renders the employee names.

This is one of the most common patterns you'll see when building React applications that consume APIs.

Building an API with Node.js and Express

APIs can be created using many backend technologies.

In the JavaScript ecosystem, Node.js and Express.js are commonly used to build APIs.

Here's a simple example:

const express = require("express");

const app = express();

app.use(express.json());

app.get("/api/employees", (req, res) => {
  res.json([
    {
      id: 1,
      name: "John",
      role: "Developer"
    }
  ]);
});

app.listen(5000, () => {
  console.log("Server running on port 5000");
});
Enter fullscreen mode Exit fullscreen mode

What's happening here?

  • Express creates the backend server.
  • /api/employees is the endpoint.
  • GET handles requests to that endpoint.
  • res.json() sends JSON data to the client.
  • The server listens on port 5000.

Now a frontend application can request:

GET /api/employees
Enter fullscreen mode Exit fullscreen mode

and receive the employee data.

A Real-World Example

Let's look at an online shopping application.

When the user opens the products page, the frontend might send:

GET /api/products
Enter fullscreen mode Exit fullscreen mode

The backend retrieves products from the database and returns:

[
  {
    "id": 1,
    "name": "Laptop",
    "price": 65000
  },
  {
    "id": 2,
    "name": "Mobile Phone",
    "price": 25000
  }
]
Enter fullscreen mode Exit fullscreen mode

The frontend displays these products.

When the user places an order:

POST /api/orders
Enter fullscreen mode Exit fullscreen mode

The backend processes the order and stores it in the database.

The complete flow is:

User
 ↓
React Frontend
 ↓
API Request
 ↓
Node.js / Express
 ↓
Database
 ↓
API Response
 ↓
React Frontend
 ↓
User
Enter fullscreen mode Exit fullscreen mode

This simple architecture is behind many real-world web applications.

API Security Best Practices

When building APIs, security should always be considered.

Some important practices include:

  • Validate user input
  • Use authentication and authorization
  • Protect sensitive information
  • Use HTTPS
  • Handle errors properly
  • Never expose database credentials
  • Implement appropriate access controls
  • Use meaningful HTTP status codes
  • Validate data on the backend

One important rule is:

Never rely only on frontend validation.

Frontend validation improves the user experience, but users can send API requests directly without using your frontend.

That's why backend validation is essential.

Where Are APIs Used?

APIs are not limited to web applications.

They're used throughout modern software development.

Web Applications

React, Angular, and Vue applications communicate with backend APIs.

Backend Applications

Node.js, Java Spring Boot, Python, and other technologies can create and consume APIs.

Mobile Applications

Android and iOS applications communicate with backend servers through APIs.

Third-Party Services

Applications can integrate with external services such as:

  • Payment systems
  • Maps
  • Email services
  • Authentication providers
  • Cloud platforms
  • Other software platforms

APIs make these integrations possible.

The Big Picture

If you're new to APIs, remember this simple model:

CLIENT
   ↓
REQUEST
   ↓
API
   ↓
BACKEND
   ↓
DATABASE
   ↓
BACKEND
   ↓
RESPONSE
   ↓
CLIENT
Enter fullscreen mode Exit fullscreen mode

The frontend doesn't need to know how the database works internally.

It needs to know how to communicate with the API:

  • Which endpoint to call
  • Which HTTP method to use
  • What data to send
  • How to authenticate
  • How to handle the response

That's the power of an API.

Final Thoughts

APIs are one of the most important concepts to understand when learning modern web development.

Once you understand:

  • REST APIs
  • HTTP methods
  • Endpoints
  • Requests and responses
  • JSON
  • Status codes
  • Authentication
  • API security

technologies like React, Node.js, Express, and databases become much easier to connect together.

But don't stop at reading.

Build an API.

Create a small Express server. Add a few endpoints. Connect it to a React application. Send requests. Inspect the responses. Handle errors.

That's when the theory starts becoming real.

If you're learning web development, APIs are a skill worth mastering.

Keep building. Keep experimenting. 🚀

Top comments (0)