REST API Tutorial for Beginners: Methods, Endpoints, JSON, CRUD and Examples

REST API Tutorial for Beginners: Methods, Endpoints, JSON, CRUD and Examples

Modern applications rarely work as a single piece of software.

A website may have a frontend, backend, database, authentication system, payment provider, cloud service and several other services working together.

One of the most common ways these components communicate is through an API.

A popular style for designing web APIs is REST.

In this beginner-friendly tutorial, you will learn:

  • What REST API means
  • How REST APIs work
  • What an endpoint is
  • HTTP methods
  • CRUD operations
  • JSON requests and responses
  • Status codes
  • Headers
  • Parameters
  • Authentication
  • API testing
  • REST API security
  • How to build a simple REST API
Beginner Tip: Before learning REST APIs, understand basic HTTP concepts such as requests, responses, URLs, headers and status codes.

What Is REST?

REST stands for Representational State Transfer.

REST is an architectural style used to design networked applications and web APIs.

REST APIs commonly use standard HTTP methods and resource-oriented URLs.

A simple REST API might look like:

GET    /users
GET    /users/10
POST   /users
PATCH  /users/10
DELETE /users/10

Here, users represents a resource and different HTTP methods represent different operations.

What Is a REST API?

A REST API is an API designed around REST principles that allows software clients to communicate with resources over a network, commonly using HTTP.

For example, a mobile application may request a list of products:

GET /api/products

The server might return:

{
  "products": [
    {
      "id": 1,
      "name": "Laptop"
    },
    {
      "id": 2,
      "name": "Keyboard"
    }
  ]
}

The application can then display the information to the user.

REST API Architecture

A common web application architecture looks like this:

Frontend
↓
REST API
↓
Backend Application
↓
Database

The frontend does not necessarily communicate directly with the database.

Instead, it sends requests to the backend API, which applies business logic and interacts with the database.

How Does a REST API Work?

The basic process is:

  1. The client creates a request.
  2. The request is sent to an API endpoint.
  3. The server receives and validates the request.
  4. The backend performs the required operation.
  5. The server creates a response.
  6. The response is sent back to the client.
  7. The client processes and displays the result.

For example:

Browser
↓
GET /api/products
↓
Backend
↓
Database
↓
JSON Response
↓
Browser

What Is a Resource in REST?

A resource is an entity that an API exposes.

Examples include:

  • Users
  • Products
  • Orders
  • Students
  • Courses
  • Payments
  • Posts
  • Comments

A REST API usually represents resources using URLs.

For example:

/users
/products
/orders
/courses
/posts

What Is an Endpoint?

An endpoint is a specific API URL through which a client can access a resource or perform a supported operation.

Example:

https://example.com/api/users

Another endpoint could be:

https://example.com/api/users/25

The first may represent a collection of users, while the second may represent one user.

REST API HTTP Methods

The HTTP method tells the server what kind of operation the client is requesting.

The most commonly used methods in CRUD-style REST APIs are:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

GET

GET is commonly used to retrieve data.

Example:

GET /api/products

Get one product:

GET /api/products/101

GET requests are generally used for retrieving information rather than changing server state.

POST

POST is commonly used to submit data or create a resource.

Example:

POST /api/products

Request body:

{
  "name": "Laptop",
  "price": 55000
}

PUT

PUT is commonly used when a client wants to replace or update a resource representation.

Example:

PUT /api/products/101

Example body:

{
  "name": "Gaming Laptop",
  "price": 75000
}

The exact update behavior depends on the API implementation.

PATCH

PATCH is commonly used for partial modifications.

Example:

PATCH /api/products/101

Request:

{
  "price": 70000
}

This example changes only the price field rather than sending the complete resource.

DELETE

DELETE is commonly used to remove a resource.

Example:

DELETE /api/products/101

Delete operations should require proper authentication and authorization.

CRUD and REST APIs

CRUD stands for:

  • Create
  • Read
  • Update
  • Delete

A basic REST API often maps these operations to HTTP methods.

CRUD HTTP Method Example
Create POST POST /products
Read GET GET /products/101
Update PUT / PATCH PATCH /products/101
Delete DELETE DELETE /products/101

What Is JSON?

JSON stands for JavaScript Object Notation.

JSON is commonly used to represent structured data exchanged between applications.

Example:

{
  "id": 101,
  "name": "Adarsh",
  "active": true,
  "skills": [
    "Python",
    "JavaScript"
  ]
}

JSON supports common data types such as strings, numbers, booleans, arrays, objects and null values.

Request vs Response

A REST API interaction usually involves two sides.

Request

The client sends information to the server.

Response

The server returns the result.

A simple request could look like:

GET /api/users/101

The response might be:

{
  "id": 101,
  "name": "Adarsh",
  "role": "developer"
}

What Are HTTP Headers?

HTTP headers carry metadata about a request or response.

Common examples include:

  • Content-Type
  • Accept
  • Authorization
  • User-Agent
  • Cache-Control

Example:

Content-Type: application/json

This indicates that the message body uses JSON.

What Is Content-Type?

The Content-Type header tells the receiving side what type of content is being sent.

Common API examples include:

Content-Type: application/json

Other media types are possible depending on the API.

What Is Accept?

The Accept header can indicate which response media types the client can handle.

Example:

Accept: application/json

What Are HTTP Status Codes?

Status codes tell the client the general outcome of a request.

Status Meaning
200 Successful request
201 Resource created
204 Successful response with no response body
400 Bad request
401 Authentication required or unsuccessful
403 Request understood but access is forbidden
404 Resource not found
409 Request conflicts with the current state
422 Request data cannot be processed by the server
429 Too many requests
500 Internal server error

What Are Query Parameters?

Query parameters are values included after a ? in a URL.

Example:

/products?category=laptops&limit=10

Here:

  • category = laptops
  • limit = 10

Query parameters are commonly used for filtering, searching, pagination and sorting.

What Are Path Parameters?

Path parameters are values included directly in the URL path.

Example:

/users/101

Here 101 can represent a specific user.

Query Parameter vs Path Parameter

Path Parameter Query Parameter
/users/101 /users?id=101
Often identifies a specific resource Often filters or modifies a collection request
Part of the resource path Appears after the question mark

What Is Request Body?

A request body contains data sent by the client to the server.

It is commonly used with POST, PUT and PATCH requests.

Example:

{
  "name": "Laptop",
  "price": 65000,
  "stock": 15
}

What Is REST API Authentication?

Some APIs are public, while others require clients to authenticate.

Authentication determines the identity associated with a request.

Authorization determines whether that identity is allowed to perform the requested operation.

Common authentication approaches include:

  • API keys
  • Bearer tokens
  • Session cookies
  • OAuth-based systems

Bearer Token Example

A token may be sent in an Authorization header:

Authorization: Bearer YOUR_TOKEN

The exact format depends on the API.

REST API Security

API security should be designed into the application from the beginning.

Important areas include:

  • Authentication
  • Authorization
  • Input validation
  • Output control
  • Rate limiting
  • HTTPS
  • Secure secret storage
  • Logging
  • Monitoring
  • Access control

Authentication Is Not Authorization

Consider a school management application.

A student may successfully log in.

That does not mean the student should be allowed to:

  • Delete another student's account
  • Modify administrator settings
  • Change exam results
  • View private administrative information

The API must enforce permissions on the server.

Validate API Input

Never assume that the client sends correct data.

For example, an API expecting:

{
  "age": 25
}

should not blindly trust that the value is a valid age.

Server-side validation should check:

  • Type
  • Format
  • Required fields
  • Length
  • Allowed values
  • Business rules

Use HTTPS

REST APIs that handle private information, credentials or authenticated sessions should normally be served over HTTPS.

HTTPS helps protect data while it is transmitted between client and server.

Protect API Credentials

Never put private API keys directly into public source code.

A bad example is:

const API_KEY = "my-secret-key";

A better architecture is to keep secrets on the server and load them from secure configuration or a secrets-management system.

What Is API Rate Limiting?

Rate limiting controls the amount of traffic a client can send.

For example, an API may define a limit such as:

100 requests per minute

Rate limiting can help protect APIs against excessive traffic, accidental overload and certain forms of abuse.

What Is API Pagination?

Returning thousands of records in one response is often inefficient.

APIs can use pagination to return smaller groups of records.

Example:

GET /products?page=1&limit=20

This could request the first page with 20 products.

What Is API Filtering?

Filtering allows clients to request only records matching specific criteria.

Example:

GET /products?category=laptop

The server can return only products matching the requested category.

What Is API Sorting?

Sorting can allow clients to control the order of returned resources.

For example:

GET /products?sort=price

The exact supported syntax depends on the API design.

REST API Versioning

APIs evolve over time.

One possible versioning strategy is:

/api/v1/users
/api/v2/users

Versioning can help manage changes while supporting older clients.

REST API Error Handling

A good API should return meaningful errors without exposing sensitive internal details.

For example:

{
  "error": {
    "code": "INVALID_EMAIL",
    "message": "Please provide a valid email address."
  }
}

Avoid returning sensitive information such as passwords, private keys, internal stack traces or database credentials.

How to Test a REST API

There are several ways to test APIs.

1. Postman

Postman provides a graphical interface for sending requests and examining API responses.

2. cURL

cURL can send HTTP requests from the command line.

Example:

curl https://example.com/api/users

3. Browser Developer Tools

Web browsers provide network tools for inspecting requests made by websites.

cURL GET Example

curl https://example.com/api/products

cURL POST Example

A JSON request can look like:

curl -X POST https://example.com/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Laptop","price":65000}'

Use these kinds of commands only with APIs and systems where you are authorized to send requests.

JavaScript REST API Example

JavaScript applications can use fetch() to communicate with APIs.

fetch("https://example.com/api/products")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

JavaScript POST Example

fetch("https://example.com/api/products", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Laptop",
    price: 65000
  })
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Production code should also handle non-success status codes and network failures appropriately.

Python REST API Example

Python applications can use HTTP libraries to communicate with REST APIs.

import requests

response = requests.get(
    "https://example.com/api/products",
    timeout=10
)

response.raise_for_status()

data = response.json()

print(data)

The timeout and error-handling approach should be adapted to your specific application.

Build a Simple REST API

One of the best ways to understand REST is to build a small project.

Let's imagine a Task Management API.

Resource

tasks

Endpoints

GET    /api/tasks
GET    /api/tasks/1
POST   /api/tasks
PATCH  /api/tasks/1
DELETE /api/tasks/1

Task Object

{
  "id": 1,
  "title": "Learn REST APIs",
  "completed": false,
  "priority": "high"
}

Building the API With Node.js

A common beginner stack is:

  • Node.js
  • Express.js
  • Database
  • REST endpoints

A minimal Express application might look like:

const express = require("express");

const app = express();

app.use(express.json());

app.get("/api/tasks", (req, res) => {
  res.json([
    {
      id: 1,
      title: "Learn REST APIs",
      completed: false
    }
  ]);
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

This is only a simple demonstration. A real application needs persistence, validation, error handling, authentication, authorization and other production controls.

Building the API With Python

Python developers can use frameworks such as FastAPI or Flask.

A basic FastAPI example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/api/tasks")
def get_tasks():
    return [
        {
            "id": 1,
            "title": "Learn REST APIs",
            "completed": False
        }
    ]

Again, this is a learning example rather than a complete production API.

Database and REST API

A REST backend commonly communicates with a database.

For example:

Client
↓
REST API
↓
Business Logic
↓
Database

Suppose the client sends:

GET /api/students/101

The backend may:

  1. Validate the request.
  2. Check authorization.
  3. Query the database.
  4. Transform the result.
  5. Return JSON.

REST API and Authentication Example

A protected endpoint might look like:

GET /api/profile

The client could send an authorization header:

Authorization: Bearer YOUR_ACCESS_TOKEN

The server should verify the credential and determine whether the user has permission to access the requested resource.

REST API and JWT

JWT stands for JSON Web Token.

JWTs are commonly used in some API authentication architectures to represent claims that can be verified by the server.

A simplified flow is:

Login
↓
Server Verifies Credentials
↓
Access Token
↓
Client Sends Token
↓
Protected API

Authentication systems need careful implementation, including token lifetime, storage, revocation strategy and authorization rules.

REST API Documentation

Good API documentation helps developers understand how to use the service.

Documentation should explain:

  • Base URL
  • Endpoints
  • HTTP methods
  • Parameters
  • Request body
  • Authentication
  • Response format
  • Status codes
  • Errors
  • Examples

OpenAPI

OpenAPI is a standard way to describe HTTP APIs in a machine-readable format.

An OpenAPI document can describe:

  • Paths
  • Methods
  • Parameters
  • Request bodies
  • Responses
  • Authentication schemes

This information can then be used by tools to generate documentation and support development workflows.

REST API Best Practices

1. Use Clear Resource Names

Prefer readable resource-oriented paths.

Example:

/users
/products
/orders

2. Use HTTP Methods Consistently

Choose methods according to the operation the endpoint represents.

3. Return Appropriate Status Codes

Use meaningful status codes so clients can understand the result.

4. Validate Input

Validate data on the server.

5. Protect Sensitive Endpoints

Apply authentication and authorization where required.

6. Use HTTPS

Protect network communication for sensitive APIs.

7. Avoid Exposing Internal Errors

Return useful client-facing error information without leaking internal implementation details.

8. Document Your API

Good documentation makes integration easier.

9. Add Rate Limits

Protect public and sensitive endpoints from excessive traffic.

10. Log Important Events

Logging can help troubleshoot problems and investigate suspicious activity.

REST API Common Mistakes

Using GET to Change Data

GET should generally be used to retrieve data rather than performing destructive changes.

Putting Secrets in URLs

Avoid placing sensitive credentials directly in URLs because URLs can be logged or exposed in unintended places.

No Authorization Checks

Always verify that the authenticated user is allowed to access or change the requested resource.

No Validation

Never trust input simply because it comes from your own frontend.

Huge Responses

Return only the data necessary for the client and consider pagination for large collections.

Poor Error Handling

Clients need consistent and understandable error responses.

REST API vs SOAP

REST and SOAP are different approaches to building networked services.

REST SOAP
Architectural style Messaging protocol
Commonly uses HTTP Can use HTTP and other transports
Often uses JSON Commonly associated with XML
Often lightweight More formal messaging model

Both approaches can be useful depending on the system and requirements.

REST API vs GraphQL

REST and GraphQL solve related API communication problems in different ways.

A REST API may expose endpoints such as:

GET /users/101
GET /users/101/orders

GraphQL commonly exposes a query interface through which clients request the fields they need.

Neither approach is automatically better for every application.

REST API vs Webhook

With a REST API, a client commonly requests information or asks a server to perform an operation.

A webhook is commonly used for event notifications, where one service sends information to another service when a specified event occurs.

Example:

Payment Completed
↓
Webhook
↓
Your Server

REST API Project Ideas

Once you understand the basics, build one of these projects:

  • Todo REST API
  • Student management API
  • Book library API
  • Expense tracker API
  • Blog API
  • Product management API
  • Movie API client
  • Weather API application
  • Job listing API
  • AI application API

Beginner REST API Project Structure

A simple project might contain:

project/
├── routes/
├── controllers/
├── models/
├── middleware/
├── services/
├── config/
├── tests/
└── server.js

The exact folder structure depends on your language and framework.

REST API Testing Checklist

Before considering an API complete, test:

  • Valid requests
  • Invalid requests
  • Missing fields
  • Invalid IDs
  • Unauthorized requests
  • Forbidden requests
  • Large inputs
  • Rate-limit behavior
  • Server errors
  • Database failures

REST API Learning Roadmap

HTTP Basics
↓
Requests & Responses
↓
JSON
↓
HTTP Methods
↓
Endpoints
↓
CRUD
↓
Authentication
↓
Database Integration
↓
API Testing
↓
API Security
↓
Documentation
↓
Build Your Own API

What Should You Learn After REST APIs?

Once you understand REST APIs, continue with:

  • Databases
  • Authentication
  • JWT
  • OAuth
  • API security
  • Testing
  • OpenAPI
  • Docker
  • Cloud deployment
  • Microservices

Final Thoughts

REST APIs are one of the most useful concepts for anyone learning modern web development.

They provide a structured way for applications to communicate with backend services.

If you understand:

Resources → Endpoints → HTTP Methods → JSON → Status Codes → Authentication

you already have a strong foundation for building and consuming web APIs.

The best way to learn REST is to stop reading after the basics and build something.

Create a small API, connect it to a frontend, store data in a database, add authentication, test the endpoints and deploy the application.

That practical experience will teach you far more than memorizing a list of HTTP methods.

CodeWithAV Tip: Build a Todo API first. Implement GET, POST, PATCH and DELETE. Then connect it to a React or JavaScript frontend. Once that works, add authentication and a database.

Frequently Asked Questions

What is a REST API?

A REST API is an API designed around REST principles and commonly uses HTTP to expose resources and operations.

What does REST stand for?

REST stands for Representational State Transfer.

What are the main REST API methods?

GET, POST, PUT, PATCH and DELETE are among the most commonly used methods in REST APIs.

What is CRUD?

CRUD stands for Create, Read, Update and Delete.

What is an API endpoint?

An endpoint is a specific URL or route through which an API exposes a resource or operation.

Why is JSON commonly used in REST APIs?

JSON provides a convenient way to represent structured data and is widely supported by modern programming languages and web technologies.

What is the difference between PUT and PATCH?

PUT is commonly used for replacing or updating a resource representation, while PATCH is commonly used for partial modifications.

What is the difference between 401 and 403?

401 generally indicates that authentication is required or was unsuccessful, while 403 generally indicates that the server understood the request but the client is not permitted to access the requested resource.

Can I build REST APIs with Python?

Yes. Frameworks such as FastAPI and Flask can be used to build REST-style APIs.

Can I build REST APIs with Node.js?

Yes. Node.js frameworks such as Express can be used to build REST APIs.

Are REST APIs secure automatically?

No. Security depends on proper authentication, authorization, validation, HTTPS, secret management, rate limiting, logging and other application controls.

Which tool can I use to test a REST API?

Postman, cURL and browser developer tools are common options for API testing and troubleshooting.

Related CodeWithAV Articles

What Is an API? Complete Beginner Guide

What Is JSON?

HTTP vs HTTPS Explained

Python Roadmap for Beginners

Web Development Roadmap for Beginners

About CodeWithAV: CodeWithAV publishes practical technology, AI, programming, cybersecurity, education, career and digital-tool resources for students, developers and professionals.
Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.

What Is an API? Complete Beginner Guide With Real-World Examples

What Is an API? Complete Beginner Guide With Real-World Examples

If you have ever used a mobile app, logged into a website, checked the weather online, made an online payment, or used an AI application, you have probably interacted with an API.

API stands for Application Programming Interface.

In simple terms, an API is a way for one software system to communicate with another software system according to defined rules.

An API allows software systems to request information or perform supported operations through a defined interface.

APIs are everywhere in modern software development. Websites, mobile applications, cloud platforms, payment systems, maps, social platforms and AI services all use APIs in different ways.

This guide explains what an API is, how APIs work, different types of APIs, REST APIs, HTTP methods, JSON, authentication, API keys, real-world examples, API security and common beginner mistakes.

What Does API Stand For?

API stands for:

Application Programming Interface

Let's understand each word.

Application

An application is a software program, service or system.

Examples include:

  • Mobile applications
  • Web applications
  • Desktop software
  • Cloud services
  • Backend systems

Programming

Programming means writing instructions that software can execute.

Interface

An interface defines how one system can interact with another system.

So an API is essentially a defined interface that software can use to communicate with another software system.

Simple Real-World Example of an API

Imagine you are using a food-delivery application.

You open the app and see:

  • Restaurants
  • Menus
  • Prices
  • Delivery information
  • Order status

The mobile app may not store all of that information itself.

It can communicate with backend services through APIs.

Mobile App
↓
API Request
↓
Backend Server
↓
Database / Services
↓
API Response
↓
Mobile App

The API acts as the communication interface between the application and the backend system.

Another Simple Example: Weather App

Suppose a weather application needs the current weather for Lucknow.

The application could send a request to a weather API:

GET /weather?city=Lucknow

The server might return data such as:

{
  "city": "Lucknow",
  "temperature": 31,
  "condition": "Clear"
}

The application can then display that information to the user.

Why Are APIs Important?

APIs allow software systems to work together without requiring every system to know how the other system is internally implemented.

For example, an application may request customer information through an API without directly managing the underlying database implementation.

APIs help with:

  • Integration
  • Data exchange
  • Automation
  • Software reuse
  • Modular architecture
  • Third-party services
  • Mobile applications
  • Cloud services

How Does an API Work?

A simple API interaction usually contains:

  1. A client sends a request.
  2. The API receives the request.
  3. The server processes it.
  4. The server may access databases or other services.
  5. The server sends a response.
  6. The client uses the response.

A simplified diagram is:

Client
↓
Request
↓
API
↓
Application Logic
↓
Database / External Service
↓
Response
↓
Client

What Is an API Request?

An API request is a message sent from a client to a server to request data or ask the server to perform a supported operation.

A request can contain:

  • URL or endpoint
  • HTTP method
  • Headers
  • Query parameters
  • Path parameters
  • Request body
  • Authentication information

What Is an API Response?

An API response is the result returned by the server.

It may contain:

  • Status code
  • Response headers
  • Data
  • Error information

For example:

{
  "id": 101,
  "name": "Adarsh",
  "role": "developer"
}

What Is an API Endpoint?

An endpoint is a specific location or route through which an API exposes a particular operation or resource.

For example:

https://example.com/api/users

This might represent a users resource.

Other endpoints might be:

/api/users
/api/products
/api/orders
/api/login
/api/profile

The exact endpoint structure depends on how the API is designed.

What Is HTTP?

Many web APIs use HTTP, the protocol used for communication between web clients and servers.

Common HTTP methods include:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

GET Method

GET is commonly used to retrieve information.

Example:

GET /api/users

This might return a list of users.

POST Method

POST is commonly used to submit data or create a resource.

Example:

POST /api/users

The request body might contain:

{
  "name": "Adarsh",
  "email": "example@example.com"
}

PUT Method

PUT is commonly used to replace or update a resource.

Example:

PUT /api/users/101

PATCH Method

PATCH is commonly used for a partial update.

Example:

PATCH /api/users/101

The request could update only a selected property:

{
  "role": "admin"
}

DELETE Method

DELETE is commonly used to remove a resource.

Example:

DELETE /api/users/101

Deleting real data should always involve appropriate authentication and authorization controls.

HTTP Methods Quick Table

Method Common Purpose
GET Retrieve data
POST Create or submit data
PUT Replace or update a resource
PATCH Partially update a resource
DELETE Delete a resource

What Is JSON?

JSON stands for JavaScript Object Notation.

JSON is commonly used to exchange structured data between applications.

Example:

{
  "name": "Adarsh",
  "age": 26,
  "skills": [
    "Python",
    "JavaScript",
    "PHP"
  ]
}

JSON is popular because it is relatively easy for humans to read and easy for software to process.

What Are HTTP Status Codes?

APIs commonly use HTTP status codes to communicate the result of a request.

Code General Meaning
200 Successful request
201 Resource successfully created
204 Successful response with no content
400 Bad request
401 Authentication required or failed
403 Request understood but not authorized
404 Resource not found
429 Too many requests
500 Server error

Status-code behavior depends on the specific API and its implementation, but these are common HTTP meanings.

What Is a REST API?

REST stands for Representational State Transfer.

REST is an architectural style commonly used for web APIs.

A REST-style API generally models resources and uses standard HTTP methods to interact with them.

For example:

GET    /api/products
GET    /api/products/10
POST   /api/products
PATCH  /api/products/10
DELETE /api/products/10

These endpoints represent operations around a products resource.

REST API Example

Suppose you are building an online bookstore.

You could have:

GET /books
GET /books/101
POST /books
PATCH /books/101
DELETE /books/101

A frontend application can use these endpoints to communicate with the backend.

What Are API Headers?

Headers provide additional information about an HTTP request or response.

Examples include:

  • Content-Type
  • Authorization
  • Accept
  • User-Agent

For example:

Content-Type: application/json

This tells the server that the request body is JSON.

What Is an API Authentication System?

Many APIs need to determine who is making a request.

Authentication answers:

Who are you?

Authorization answers:

What are you allowed to do?

These are different concepts.

Common API Authentication Methods

API Keys

An API key is a credential issued by a service and used to identify or authorize requests, depending on the API's design.

Example:

Authorization: Bearer YOUR_TOKEN

The exact authentication format varies between APIs.

Bearer Tokens

Bearer tokens are often sent through an HTTP Authorization header.

Session Cookies

Web applications may use cookies to associate a browser session with an authenticated user.

OAuth

OAuth is a framework commonly used to allow applications to obtain delegated access to resources without requiring users to share their passwords with the client application.

OAuth implementations can be more complex than simple API keys and should be designed carefully.

What Is an API Key?

An API key is a secret or semi-secret credential provided by an API service for identifying or controlling requests.

A typical API request might include a key through a header or query parameter, depending on the API design.

Never publish private API keys inside public source-code repositories.

Why Should API Keys Be Protected?

If an attacker gets access to a private API key, they may be able to use the associated service under the permissions attached to that credential.

Depending on the service, this may cause:

  • Unexpected charges
  • Data access
  • Unauthorized requests
  • Account abuse
  • Quota exhaustion

Use environment variables or an appropriate secrets-management system rather than hard-coding sensitive credentials into public code.

What Is API Rate Limiting?

Rate limiting controls how many requests a client can make during a defined period or under defined conditions.

For example:

100 requests per minute

Rate limits can help protect services from excessive traffic and accidental or malicious abuse.

What Is an API Request Body?

The request body contains data sent to the server, commonly with methods such as POST, PUT or PATCH.

Example:

{
  "name": "Laptop",
  "price": 55000,
  "category": "Computers"
}

What Are Query Parameters?

Query parameters provide additional information in a URL.

Example:

/products?category=laptops&limit=10

Here:

  • category = laptops
  • limit = 10

What Are Path Parameters?

Path parameters are values included in the URL path.

Example:

/users/101

Here 101 may represent a specific user ID.

API vs Database

These are not the same thing.

A database stores and organizes data.

An API provides a controlled interface through which software can access or manipulate supported information and operations.

A common architecture is:

Frontend
↓
API
↓
Backend
↓
Database

API vs Web Application

A web application typically provides a user interface for humans.

An API often provides an interface intended for software clients.

However, a web application and its APIs may exist together as parts of the same system.

What Is an Internal API?

An internal API is used within an organization or software architecture.

For example:

Authentication Service → User Service → Order Service → Payment Service

Different internal services can communicate through defined interfaces.

What Is a Public API?

A public API is made available to external developers or customers according to the provider's terms and access rules.

Examples can include APIs for:

  • Maps
  • Payments
  • Messaging
  • Weather
  • Social platforms
  • AI services

What Is a Private API?

A private API is restricted to a specific organization, application, team or environment.

It may be used to connect internal software systems.

What Is a Third-Party API?

A third-party API is provided by another organization and integrated into your application.

For example, a developer might use an external service for:

  • Payments
  • Email delivery
  • Maps
  • Authentication
  • AI models
  • Analytics

This allows developers to use specialized services instead of building every feature themselves.

API Example Using JavaScript

Modern JavaScript applications can use fetch() to make HTTP requests.

fetch("https://example.com/api/users")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

The example requests data and then converts a JSON response into a JavaScript value.

API Example Using Python

Python developers can use an HTTP library such as requests for API communication.

import requests

response = requests.get("https://example.com/api/users")

print(response.status_code)
print(response.json())

For production applications, proper timeout handling, error handling, authentication and response validation should also be implemented.

API Testing Tools

Developers often use dedicated tools to test APIs.

Postman

Postman provides a graphical interface for sending requests and inspecting responses.

cURL

cURL is a command-line tool that can communicate with HTTP services.

Example:

curl https://example.com/api/users

Browser Developer Tools

Web browsers provide network-development tools that let developers inspect requests and responses made by web applications.

What Is API Documentation?

API documentation explains how developers should use an API.

Good API documentation usually explains:

  • Available endpoints
  • HTTP methods
  • Parameters
  • Authentication
  • Request examples
  • Response examples
  • Error responses
  • Rate limits

Well-written documentation can significantly reduce integration problems.

OpenAPI and Swagger

OpenAPI is a specification for describing HTTP APIs in a machine-readable format.

Tools in the Swagger ecosystem can be used to document, visualize and interact with API definitions.

A small OpenAPI definition might describe:

  • Available paths
  • Methods
  • Parameters
  • Request bodies
  • Responses
  • Authentication schemes

What Is API Versioning?

APIs may change over time.

For example:

/api/v1/users
/api/v2/users

Versioning can help providers introduce changes while supporting clients that still depend on an older interface.

The exact versioning strategy depends on the API architecture.

What Is API Security?

APIs are part of an application's attack surface, so security should be considered from the beginning.

Important areas include:

  • Authentication
  • Authorization
  • Input validation
  • Output validation
  • Rate limiting
  • Logging
  • Monitoring
  • Transport security
  • Secret management

Authentication vs Authorization

Remember the difference:

Authentication = Who are you?

Authorization = What are you allowed to do?

For example, a user may be authenticated successfully but still not have permission to delete another user's account.

Why Input Validation Matters

Never assume that data received through an API is safe.

Validate inputs such as:

  • Names
  • Emails
  • IDs
  • Numbers
  • Dates
  • File names
  • Search parameters

Validation should happen on the server side even when the client also validates input.

Why HTTPS Matters for APIs

APIs commonly transmit data over HTTPS so communication can be protected while traveling across the network.

This is particularly important for:

  • Authentication credentials
  • User information
  • Session data
  • Payment-related data
  • Private application information

Common API Security Mistakes

1. Exposing API Keys

Never publish private credentials in public repositories.

2. Missing Authorization Checks

Do not assume that authentication automatically gives access to every resource.

3. Trusting Client Input

Validate data on the server.

4. Returning Excessive Data

Return only information that the client actually needs.

5. Missing Rate Limits

High-volume requests can create reliability and abuse problems.

6. Weak Logging

Important API actions should be observable and auditable.

What Is an API Gateway?

An API gateway is a component that can sit between clients and backend services.

Depending on the architecture, it may handle:

  • Routing
  • Authentication
  • Rate limiting
  • Logging
  • Request transformation
  • Traffic management

A simplified architecture can look like:

Client
↓
API Gateway
↓
Service A / Service B / Service C

API Architecture Example

A typical web application might look like:

React / Mobile App
↓
REST API
↓
Node.js / Python / PHP Backend
↓
PostgreSQL / MySQL / MongoDB

The exact architecture depends on the application.

APIs in AI Applications

Modern AI applications also use APIs extensively.

An application may call an AI model through an API rather than running the entire model itself.

A simplified workflow can be:

User
↓
Your Application
↓
AI API
↓
AI Model
↓
Response
↓
Your Application

This architecture allows developers to integrate AI capabilities into websites, applications and automation systems.

APIs in Mobile Applications

Mobile applications often communicate with backend systems through APIs.

For example:

Mobile App → Login API → Authentication Service

Mobile App → Products API → Product Database

Mobile App → Orders API → Order System

This allows the mobile application to exchange information with backend services.

APIs in Payment Systems

Online applications can integrate payment providers through APIs.

A simplified flow can be:

  1. User starts checkout.
  2. Your application creates a payment request.
  3. The payment provider processes the request.
  4. The provider returns a result.
  5. Your application updates the order status.

Real payment integrations require careful security, authentication, validation, error handling and compliance with the provider's requirements.

APIs in Maps and Location Services

Applications can use mapping APIs to integrate capabilities such as:

  • Maps
  • Geocoding
  • Directions
  • Distance calculations
  • Place information

This allows developers to build location-aware applications without creating a mapping platform from scratch.

Benefits of APIs

  • Integration: Connect different systems.
  • Reuse: Expose functionality that multiple applications can use.
  • Modularity: Separate application components.
  • Automation: Let software communicate automatically.
  • Scalability: Support different clients and services.
  • Innovation: Allow developers to build on top of existing platforms.

API Limitations

APIs also introduce challenges.

  • Network failures
  • Rate limits
  • Authentication complexity
  • Version changes
  • Third-party dependency
  • Latency
  • Security risks
  • Service availability issues

When you depend on a third-party API, your application can be affected by changes in the provider's availability, terms or interface.

API vs SDK

An API and an SDK are related but different.

An API defines an interface for interacting with a service or software component.

An SDK, or Software Development Kit, is a collection of tools, libraries, documentation and other resources designed to help developers build applications for a particular platform or service.

An SDK may provide convenient wrappers around APIs.

API vs Library

A library is reusable code that your application can include and call.

An API defines how software components can interact.

A library can expose an API for developers to use.

API vs Webhook

An API generally involves a client asking a server for information or asking it to perform an operation.

A webhook is commonly used when a service sends information to another system automatically when a particular event happens.

For example:

Payment Completed
↓
Webhook
↓
Your Server

The exact behavior depends on the service implementation.

How Beginners Should Learn APIs

A practical learning path is:

HTTP Basics
↓
URLs & Endpoints
↓
GET / POST / PUT / PATCH / DELETE
↓
JSON
↓
Headers
↓
Status Codes
↓
Authentication
↓
REST APIs
↓
API Testing
↓
API Security
↓
Build Your Own API

Build Your First Simple API

A beginner project could be a Task Management API.

Possible endpoints:

GET    /tasks
GET    /tasks/1
POST   /tasks
PATCH  /tasks/1
DELETE /tasks/1

The API could manage:

  • Task title
  • Description
  • Status
  • Priority
  • Due date

You could build it using:

  • Python + FastAPI
  • Node.js + Express
  • PHP
  • Java + Spring Boot

Choose a stack that matches your learning goals.

API Practice Project Ideas

  • Student management API
  • Todo API
  • Book library API
  • Expense tracker API
  • Weather dashboard using a public API
  • Movie search application using an API
  • AI-powered application using an AI API
  • Developer portfolio backend API

API Testing Checklist

When testing an API, check:

  • Successful requests
  • Invalid input
  • Missing parameters
  • Unauthorized requests
  • Forbidden requests
  • Missing resources
  • Unexpected data types
  • Rate-limit behavior
  • Error messages

Common Beginner API Mistakes

1. Not Understanding HTTP

Learn request methods, headers, status codes and response bodies first.

2. Hard-Coding Secrets

Use secure secret storage.

3. Ignoring Errors

Your application should handle failed requests gracefully.

4. Trusting the Client

Server-side validation and authorization are essential.

5. Returning Too Much Information

Expose only data that is actually required.

6. Not Reading Documentation

Always read the provider's official API documentation before integration.

Final Thoughts

APIs are one of the foundations of modern software development.

They allow websites, mobile apps, backend services, cloud platforms, AI systems and third-party services to communicate using defined interfaces.

Once you understand:

Requests → Endpoints → HTTP Methods → JSON → Responses → Authentication

many modern application architectures become much easier to understand.

If you are learning web development, APIs should be one of the next topics you master after basic HTTP and programming.

CodeWithAV Tip: Don't learn APIs only by reading. Open Postman or use cURL, send a few requests, inspect the headers and status codes, and then build a small API yourself.

Frequently Asked Questions

What is an API in simple words?

An API is a defined interface that allows one software system to communicate with another software system.

What does API stand for?

API stands for Application Programming Interface.

What is a REST API?

A REST API is a web API designed according to REST architectural principles and commonly uses HTTP methods to work with resources.

What is an API endpoint?

An endpoint is a specific API route through which a client can access a supported resource or operation.

What is JSON used for in APIs?

JSON is commonly used to represent and exchange structured data between applications.

What are GET and POST?

GET is commonly used to retrieve data, while POST is commonly used to submit data or create a resource.

What is an API key?

An API key is a credential provided by an API service to identify or control access to requests, depending on the service's design.

Is an API the same as a database?

No. A database stores data, while an API provides an interface through which applications can interact with supported data and operations.

Can APIs be used with Python?

Yes. Python provides many libraries and frameworks that can consume and create APIs.

Can APIs be used with JavaScript?

Yes. JavaScript applications commonly communicate with APIs using HTTP requests such as those made with fetch().

Are APIs secure automatically?

No. API security depends on proper authentication, authorization, validation, transport security, secret management, rate limiting, monitoring and other controls.

Related CodeWithAV Articles

How the Internet Works: Complete Beginner Guide

HTTP vs HTTPS Explained

What Is JSON?

REST API Tutorial for Beginners

Python Roadmap for Beginners

About CodeWithAV: CodeWithAV publishes practical technology, AI, programming, cybersecurity, education, career and digital-tool resources for students, developers and professionals.
Adarsh verma

Adarsh verma

CodeWithAV publishes practical technology tutorials, study resources, programming guides, and cybersecurity learning content.