Understanding APIs: A Developer’s Guide to Building and Using APIs

Understanding APIs: A Developer’s Guide to Building and Using APIs

Introduction to APIs:

An Application Programming Interface (API) acts as a bridge between different software applications, allowing them to communicate with each other. Think of an API like a waiter in a restaurant — customers (the client application) don’t need to know how the kitchen (the server) prepares their food; they need to know how to place their order through the waiter (the API).

I designed and developed an e-commerce web application with HTML, CSS, and JavaScript for the front end, Python for the back end, and MySQL for the database. I will use this as an example to explain the core concepts of APIs.

E-commerce Web Application API Flow Chart:

Home Page:

Product Catalog Page:

Cart Page:

Order Page:

Sign Up Page:

Login Page:

To check the complete source code:

https://github.com/SubbuTechOps/python-app-docker-compose.git

APIs in the E-Commerce Application

This E-Commerce application consists of the following API endpoints:

1. Authentication API (auth_routes)

  • User Login: /api/auth/login (POST) → Authenticates users and starts a session.

  • User Logout: /api/auth/logout (POST) → Clears session and logs out users.

2. Product API (product_routes)

  • Get All Products: /api/products (GET) → Returns a list of products.

  • Get Product Details: /api/products/<int:product_id> (GET) → Fetches details of a specific product.

3. Cart API (cart_routes)

  • View Cart: /api/cart (GET) → Returns the current user's cart.

  • Add to Cart: /api/cart (POST) → Adds a product to the cart.

  • Remove from Cart: /api/cart/<int:item_id> (DELETE) → Removes an item from the cart.

4. Order API (order_routes)

  • Place Order: /api/orders (POST) → Places an order with the items in the cart.

  • Get Order Details: /api/orders/<int:order_id> (GET) → Fetches details of a specific order.

5. Health Check API

  • Check API Status: /api/health (GET) → Provides API uptime, session data, and frontend path.

6. Static Files API

  • Serve Static Files: /<path:filename> (GET) → Serves frontend files.

  • Serve Index Page: / (GET) → Serves index.html or API running message.

Error Handling:

  • 404 Not Found: Handles missing resources.

  • 500 Internal Server Error: Handles unexpected issues.

  • 400 Bad Request: Handles invalid requests.

Core Concepts:

What Makes Up an API?

An API consists of several key components that work together:

  1. Endpoints: These are the URLs where the E-Commerce API can be accessed. Similar to a store address, each endpoint serves a specific purpose. For example,
    📌 https://api.ecommerce.com/products → Retrieves a list of available products.
    📌 https://api.ecommerce.com/cart → Fetches the current user's shopping cart details.
    📌 https://api.ecommerce.com/orders → Handles order-related operations.

2. Methods: These actions can be performed on the allowed endpoints. They’re like verbs telling the API what to do with the data.

  • GET → Read data (View products, orders, cart items).

  • POST → Create new data (Add product, register user, place order).

  • PUT → Update existing data (Update profile, modify cart quantity).

  • DELETE → Remove data (Delete cart item, cancel order).

3. Parameters: Additional data is sent to fine-tune the API request, such as specifying which page of results you want to see.

  • Definition: Parameters are extra details added to an API request to filter or refine the results.

  • Example in E-Commerce:

  • Fetch only the first page of products:

GET /api/products?page=1

Search for laptops only:

GET /api/products?category=laptops

4. Authentication: Security measures ensure that only authorized users can access the API.

  • Definition: Ensures that only authorized users can access the API.

  • Example in E-Commerce:

When a user logs in, the API gives a token:

{
  "message": "Login successful",
  "token": "eyJhbGciOiJIUz..."
}

To add a product to the cart, the request must include this token:

POST /api/cart/add
Authorization: Bearer eyJhbGciOiJIUz...

Why? Prevents unauthorized access and protects user data.

5. Response Format: The structure of the data returned by the API, commonly in formats like JSON or XML.

  • Definition: The structure of the data sent back by the API.

  • Common Format: JSON (because it’s easy to read and use).

Example in E-Commerce:

  • Fetch product details
GET /api/products/1

Response in JSON:

{
  "id": 1,
  "name": "Laptop",
  "price": 799.99,
  "stock": 20
}

Why? Frontend uses this data to display products to users.

API Types:

What are the API Types?

APIs are classified according to their usage patterns and architectures.

API Types According to Purposes of Use

🔹 Internal API — Used within a company, hidden from public access. Helps teams share data securely.

🔹 Open API (Public API) — Available to everyone, can be free or paid. Example: Google Maps API.

🔹 Partner API — Used between business partners for secure data exchange. Example: E-commerce & shipping company integration.

🔹 Composite API — Combines multiple APIs into one request for efficiency. Example: Fetching account balance + transaction history in one call.

API Types According to Architectural Structure:

1. Web APIs (HTTP/HTTPS APIs)

These are the most common APIs, operating over the internet using HTTP protocols. They come in several varieties:

1.1. REST (Representational State Transfer):

The most popular type of web API today. REST APIs follow these principles:

  • Stateless: Each request contains all the information needed

  • Resource-based: Everything is treated as a resource with a unique URL

  • Uses standard HTTP methods (GET, POST, PUT, DELETE)

  • Supports multiple data formats (usually JSON)

Example REST API Request in an E-Commerce Web Application:

Get All Products:

This request fetches all available products from the online store.

Request (Client → Server)

GET /api/products HTTP/1.1
Host: api.ecommerce.com
Authorization: Bearer <User_Token>
Content-Type: application/json

Response (Server → Client)

[
    {"id": 1, "name": "iPhone 15", "price": 999.99, "stock": 20},
    {"id": 2, "name": "Samsung Galaxy S24", "price": 899.99, "stock": 15}
]

📌 Step-by-Step Flow: How catalog.html Fetches and Displays Products

1️⃣ User Visits catalog.html

  • The user opens the Product Catalog page in their browser (http://52.90.222.178:5000/catalog.html).

  • The browser sends a request to fetch product data.

2️⃣ Frontend (JavaScript) Sends an API Request

  • JavaScript code in catalog.html makes a GET request to the Flask API endpoint /api/products.

3️⃣ Backend API (GET /api/products) Fetches Data

  • The get_all_products() function runs when the frontend calls /api/products.

4️⃣ Database Retrieves Product Information

  • The backend queries the Product table in the database

  • Example database response:

[
    {"id": 1, "name": "Laptop", "price": 799.99},
    {"id": 2, "name": "Smartphone", "price": 499.99}
]

5️⃣ Frontend Renders Product Data in catalog.html

  • The JavaScript loops through the JSON response and dynamically creates HTML elements to display products.

Example rendered HTML:

<div class="product-card">
  <h3>Laptop</h3>
  <p>Price: $799.99</p>
  <button onclick="addToCart(1)">Add to Cart</button>
</div>
<div class="product-card">
  <h3>Smartphone</h3>
  <p>Price: $499.99</p>
  <button onclick="addToCart(2)">Add to Cart</button>
</div>

1.2. SOAP (Simple Object Access Protocol):

SOAP has strict rules and rigid messaging standards that can make it more secure than protocols such as REST. These types of APIs are frequently used in enterprise applications, particularly for payment processing and customer management, as they are highly safe in nature.

A more rigid, protocol-specific API style used in enterprise environments:

  • Uses XML exclusively

  • Highly structured messaging

  • Built-in error handling

  • Better security features

Example SOAP request:

<soap:Envelope>
  <soap:Header>
    <Authorization>Bearer abc123</Authorization>
  </soap:Header>
  <soap:Body>
    <GetUser>
      <UserId>123</UserId>
    </GetUser>
  </soap:Body>
</soap:Envelope>

1.3. GraphQL:

A modern API query language that gives clients more control:

  • Clients specify precisely what data they need

  • Single endpoint for all requests

  • Reduces over-fetching and under-fetching of data

Facebook initially developed GraphQL to simplify endpoint management for REST-based APIs. Instead of maintaining multiple endpoints with small amounts of disjointed data, GraphQL provides a single endpoint that inputs complex queries and outputs only as much information as is needed for the query.

Example GraphQL query:

query {
  user(id: "123") {
    name
    email
    posts {
      title
    }
  }
}

2. Library/SDK APIs

These are programming interfaces provided by software libraries or frameworks:

  • Used directly in your code

  • No network requests are needed

  • Usually specific to a programming language

Example using a Python library API:

import pandas as pd

# Using pandas API to read a CSV file
df = pd.read_csv('data.csv')

3. Operating System APIs

These allow applications to interact with the operating system:

  • File system operations

  • Process management

  • Device control

  • System settings

Example using Python’s OS API:

import os

# Using OS API to create a directory
os.mkdir('new_folder')

API Protocols:

1. HTTP/HTTPS

The foundation of web APIs, using well-defined methods and status codes:

Methods:

  • GET: Retrieve data

  • POST: Create new data

  • PUT: Update existing data

  • DELETE: Remove data

  • PATCH: Partially update data

Status Codes:

  • 2xx: Success (e.g., 200 OK)

  • 3xx: Redirection

  • 4xx: Client errors

  • 5xx: Server errors

2. WebSocket

Enables real-time, two-way communication:

  • Persistent connection

  • Lower latency than HTTP

  • Ideal for chat apps and live updates

Example WebSocket connection:

const ws = new WebSocket('wss://api.example.com/chat');
ws.onmessage = (event) => {
    console.log('Received:', event.data);
};

3. gRPC

gRPC (Google Remote Procedure Call) is a modern, high-performance framework for inter-service communication in microservices architecture. Unlike REST APIs that use HTTP + JSON, gRPC uses Protocol Buffers (Protobuf), making it faster and more efficient.

Google’s high-performance RPC framework:

  • Uses Protocol Buffers

  • Supports streaming

  • Excellent for microservices

Example Protocol Buffer definition:

📌 How gRPC Works in a Web Application

In an E-Commerce Application, gRPC can be used for fast communication between microservices.

Example Use Case:
A frontend web app must fetch a product catalog from the backend Product Service.

1️⃣ Defining gRPC Service (product.proto)

gRPC services use Protocol Buffers (Protobuf) to define API contracts.

This defines:

  • GetAllProducts(): Returns a list of products.

  • GetProductById(): Fetches a single product by ID.

  • Product: Defines the product structure.

2️⃣ Implementing gRPC Server (product_server.py)

The gRPC server implements the service logic.

Key Features:

  • Implements ProductService methods (GetAllProducts, GetProductById).

3️⃣ Implementing gRPC Client (product_client.py)

The client calls the gRPC server to fetch data.

Key Features:

  • Calls GetAllProducts() to fetch all products.

  • Calls GetProductById() to fetch a single product.

4️⃣ Running gRPC Server & Client

# 1. Generate Python code from Protobuf
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. product.proto

# 2. Start gRPC Server
python product_server.py

# 3. Run gRPC Client
python product_client.py

Output:

ProductService gRPC Server is running on port 50051...
Product List: products {
  id: 1
  name: "Laptop"
  price: 799.99
}
products {
  id: 2
  name: "Smartphone"
  price: 499.99
}

API Methods

HTTP Methods:

1. GET: Used to retrieve data

It is a request used to retrieve data. Never used to delete, update or insert data.

  • Safe and idempotent

  • Should not modify data

  • Can be cached

Example:

Product API in E-Commerce Web Application

Example: Get Products

GET /api/products
curl -X GET http://52.90.222.178:5000/api/products

Example: Response

[
   {"id": 1, "name": "iPhone 15", "price": 999.99},
   {"id": 2, "name": "Samsung Galaxy S24", "price": 899.99}
]

If the API returns JSON, you can format the response using jq:

curl -X GET http://52.90.222.178:5000/api/products | jq

Debugging & Troubleshooting

If you’re not getting the expected response, check:

Is the Flask server running?

curl -X GET http://52.90.222.178:5000/api/health

How the /api/health Endpoint Works in Flask

The /api/health endpoint is a health check API that provides the current status of the application, including uptime and session state. It helps in monitoring the system and ensuring that the API is running properly.

I have configured this /api/health endpoint in my E-Commerce Web Application.

@app.route("/api/health", methods=["GET"])
def health_check():
    uptime = time.time() - start_time
    return jsonify({
        "status": "healthy",
        "uptime": f"{uptime:.2f} seconds",
        "session_active": "username" in session
    }), 200

2. POST: Creates new resources

The POST method is a request used to insert data. Posted data type — JSON.

  • Not idempotent

  • Creates new resources

  • Cannot be cached

Example: Authentication Endpoints

This is handled in auth_routes.py, prefixed with /api/auth.

User clicks “Login” → The frontend sends a request to the backend API (POST /api/auth/login). This is handled in auth_routes.py, prefixed with /api/auth.

✔ How It Works?

  1. User sends a POST request to /api/auth/login with username & password.

  2. If credentials are valid:

  • The user session is stored.

  • API returns a success message.

3. If credentials are invalid:

  • API returns 401 Unauthorized.

Example: Response

3. PUT : Updates existing resources

PUT method is used to create or update (replace) a resource. Useful for syncing data.

  • Idempotent

  • Replaces entire resource

  • It cannot be cached

Ex: We can add a “Change Password” feature for an existing user using a PUT /api/auth/change-password API endpoint.

Steps to Implement “Change Password” API

  1. The user sends a PUT request with their old and new password.
curl -X PUT http://localhost:5000/api/auth/change-password 
     -H "Content-Type: app
     -d '{"old_password": "currentPass123", "new_password": "newPass456"}'

2. API verifies the old password:

  • If incorrect, return an error (401 Unauthorized).

3. If correct, update the password in the database.

4. Save the new password (after hashing it for security).

5. Return a success message.

{"message": "Password changed successfully"}

In an e-commerce application like yours, a PUT method would typically be used in:

  1. Updating User DetailsPUT /api/auth/update-profile

  2. Updating Product Information (Admin)PUT /api/products/<product_id>

  3. Updating Cart ItemsPUT /api/cart/<cart_id>

  4. Updating an Order StatusPUT /api/orders/<order_id>

4. DELETE: Removes resources

The DELETE method deletes the specified resource.

  • Idempotent

  • Removes the resource

  • Cannot be cached

Example: DELETE /api/cart API to Remove a Product from the Cart

1️⃣ Endpoint Definition (Flask API):

@cart_bp.route('/cart', methods=['DELETE'])
def remove_from_cart():
    """
    Remove a product from the cart for the logged-in user.
    Expects JSON payload: { product_id }.
    """
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({"message": "User not authenticated"}), 401

        data = request.json
        product_id = data.get('product_id')

        if not product_id:
            return jsonify({"message": "'product_id' is required"}), 400

        connection = get_db_connection()
        cursor = connection.cursor()

        delete_query = "DELETE FROM cart_items WHERE user_id = %s AND product_id = %s"
        cursor.execute(delete_query, (user_id, product_id))

        if cursor.rowcount == 0:
            return jsonify({"message": "Product not found in cart"}), 404

        connection.commit()
        return jsonify({"message": "Product removed from cart successfully"}), 200
    except Exception as e:
        return jsonify({"message": "Failed to remove product from cart", "error": str(e)}), 500
    finally:
        close_db_connection(connection)

2️⃣ How This Works

  1. User sends a DELETE request with the product_id they want to remove.

  2. API verifies if the user is logged in (checks session['user_id']).

  3. Checks if the product_id is valid (if missing, returns 400 Bad Request).

  4. Executes SQL DELETE query to remove the product from the cart_items table.

  5. If the product does not exist, it returns 404 Not Found.

  6. If successful, it commits the transaction and returns a success message (200 OK).

  7. Handles database errors and ensures the connection is closed.

3️⃣ Example API Request & Response:

Request:

Now User wanted to delete iPhone 15 Pro from the cart:

Method 1: Using the UI

  • Click the “Remove” button under “iPhone 15 Pro”.

  • The item should disappear, and the cart total should update.

Method 2: Using cURL

Run this command in the terminal:

curl -X DELETE http://52.90.222.178:5000/api/cart 
     -H "Content-Type: application/json" 
     -H "Cookie: session=00068d4c-4b41-4e3e-8884-7389cabbb9b0"
     -d '{"product_id": 4}'

Responses:

Success (200 OK):

{
    "message": "Product removed from cart successfully"
}

After deletion of that item:

5. PATCH: Partially updates resources

PATCH method is to request used to update data. Only passed data will be updated. You don’t need to provide all the data set.

  • Not idempotent

  • Updates part of resource

  • Cannot be cached

The PATCH method is used to partially update a resource. Instead of sending the entire data set, we only send the fields that need to be updated.

Use Case: Updating a User’s Profile (PATCH /api/auth/update-profile)

Imagine a user wants to update only their email or password without changing their username.

1️⃣ PATCH Endpoint: PATCH /api/auth/update-profile

2️⃣ Sending a PATCH Request

If the user wants to update only their email:

Using cURL:

curl -X PATCH http://52.90.222.178:5000/api/auth/update-profile \
     -H "Content-Type: application/json" \
     -H "Cookie: session=your_valid_session_id" \
     -d '{"email": "newemail@example.com"}'

🔹 Only the email field will be updated.

3️⃣ Expected Responses

If update is successful:

{
    "message": "Profile updated successfully"
}

If no fields are provided:

{
    "message": "No valid fields provided for update"
}

If session is missing:

{
    "message": "User not authenticated"
}

4️⃣ Why Use PATCH Instead of PUT?

Conclusion: Understanding APIs, Endpoints, and Methods in Web Development

APIs (Application Programming Interfaces) allow different systems to communicate with each other. They define how requests and responses are exchanged between a client (browser, app) and a server.

Key Takeaways:

1. What is an API?

  • An API acts as a bridge between two applications, enabling data exchange.

  • Example: A shopping website uses an API to fetch product details from a database.

2. API Endpoints

  • An endpoint is a URL that clients use to request or send data.

  • Example: GET /api/products retrieves all products.

3. Types of APIs

  • REST API → Uses HTTP methods (GET, POST, PUT, DELETE) to manage data.

  • GraphQL API → Lets clients request specific data fields, reducing unnecessary data transfer.

  • SOAP API → Uses XML messaging, mainly in enterprise applications.

  • WebSocket API → Maintains a continuous connection for real-time updates (e.g., live chat).

4. HTTP Methods in APIs

5. Secure APIs

  • Use authentication (JWT, API Keys, OAuth) to restrict access.

  • Protect sensitive data with HTTPS encryption.

  • Implement rate limiting to prevent abuse.

Final Thought

APIs are the backbone of modern applications, enabling data sharing between different services. Developers create smooth and efficient digital experiences by designing well-structured and secure APIs.

Your Thoughts Matter!

I’d love to hear what you think about this article — feel free to share your opinions in the comments below (or above, depending on your device!). If you found this helpful or enjoyable, a clap, a comment, or a highlight of your favourite sections would mean a lot.

For more insights into the world of technology and data, visit subbutechops.com*.* There’s plenty of exciting content waiting for you to explore!

🔔 Subscribe for more DevOps, Shell Scripting, and Kubernetes tutorials:
👉 https://www.youtube.com/@SubbuTechTutorials

Thank you for reading, and happy learning! 🚀