What Is JSON? Complete Beginner Guide With Examples

If you have worked with APIs, JavaScript, web development, or backend programming, you have probably seen something that looks like this:

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

This format is called JSON.

JSON is one of the most commonly used formats for representing and exchanging structured data between software systems. It is especially common in web APIs, configuration files, applications, and data-processing workflows.

In this beginner-friendly guide, you will learn what JSON means, how its syntax works, the difference between objects and arrays, nested JSON, data types, JSON in APIs, common mistakes, JSON vs XML, and practical examples.

Simple Definition: JSON stands for JavaScript Object Notation. It is a text-based format used to represent structured data in a way that is relatively easy for people and software to read and process.



What Does JSON Stand For?

JSON stands for JavaScript Object Notation.

Despite its name, JSON is not limited to JavaScript. JSON data can be processed by many programming languages, including Python, Java, C#, PHP, Go, Ruby, and many others.

Why Is JSON So Popular?

JSON is popular because it is:

  • Easy for humans to read
  • Easy for programs to parse
  • Compact compared with many older data formats
  • Widely supported by programming languages
  • Commonly used by web APIs
  • Suitable for nested and structured information

What Does JSON Look Like?

Here is a simple JSON object:

{
  "name": "Rahul",
  "age": 22,
  "city": "Prayagraj"
}
  

This data contains three properties:

  • name → Rahul
  • age → 22
  • city → Prayagraj

JSON Object

A JSON object is enclosed in curly braces:

{
  "key": "value"
}
  

An object contains one or more key-value pairs.

For example:

{
  "username": "adarsh",
  "role": "developer"
}
  

Here:

  • username is the key.
  • adarsh is the value.
  • role is another key.
  • developer is its value.

What Is a JSON Key?

A key identifies a piece of data inside a JSON object.

For example:

{
  "email": "user@example.com"
}
  

email is the key.

In standard JSON syntax, object member names are written as strings using double quotation marks.

What Is a JSON Value?

A value is the data associated with a key.

JSON supports several important value types.

JSON Data Types

The main JSON value types are:

  • String
  • Number
  • Object
  • Array
  • Boolean
  • Null

1. String

A string contains text and is enclosed in double quotes.

{
  "name": "Adarsh"
}
  

2. Number

JSON supports numeric values without quotes.

{
  "age": 25,
  "price": 1499.50
}
  

3. Boolean

Boolean values are either true or false.

{
  "isStudent": true,
  "isBlocked": false
}
  

4. Null

null represents the absence of a value.

{
  "middleName": null
}
  

5. Array

An array contains an ordered collection of values and is enclosed in square brackets.

{
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ]
}
  

6. Object

An object can itself be used as a value inside another object.

{
  "user": {
    "name": "Adarsh",
    "role": "Developer"
  }
}
  

JSON Objects vs JSON Arrays

Two of the most important JSON structures are objects and arrays.

JSON Object

Objects use curly braces:

{
  "name": "Adarsh",
  "age": 25
}
  

JSON Array

Arrays use square brackets:

[
  "Python",
  "JavaScript",
  "SQL"
]
  

An array can also contain objects.

[
  {
    "id": 1,
    "name": "Rahul"
  },
  {
    "id": 2,
    "name": "Anita"
  }
]
  

Nested JSON

JSON can represent complex structures by placing objects and arrays inside other objects and arrays.

Example:

{
  "name": "Adarsh",
  "contact": {
    "email": "user@example.com",
    "phone": "9876543210"
  },
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ]
}
  

Here, contact contains another JSON object and skills contains an array.

JSON Syntax Rules

Although JSON is simple, its syntax is strict.

Rule 1: Use Double Quotes for Object Keys

Correct:

{
  "name": "Adarsh"
}
  

Using an unquoted key is not valid standard JSON:

{
  name: "Adarsh"
}
  

Rule 2: Separate Properties With Commas

Correct:

{
  "name": "Adarsh",
  "age": 25
}
  

Rule 3: Do Not Add a Trailing Comma

This is invalid standard JSON:

{
  "name": "Adarsh",
  "age": 25,
}
  

The comma after 25 should be removed.

Rule 4: Strings Use Double Quotes

Standard JSON uses double quotation marks for strings.

Rule 5: Boolean Values Are Lowercase

Use:

true
false
  

Not:

True
False
  

Rule 6: Null Is Lowercase

null
  

Complete JSON Example

{
  "id": 101,
  "name": "Adarsh Verma",
  "age": 25,
  "isStudent": true,
  "email": "user@example.com",
  "phone": null,
  "skills": [
    "Python",
    "JavaScript",
    "SQL"
  ],
  "address": {
    "city": "Prayagraj",
    "state": "Uttar Pradesh",
    "country": "India"
  }
}
  

This example demonstrates numbers, strings, booleans, null, arrays, and nested objects.

JSON in REST APIs

JSON is commonly used as the format for request and response bodies in REST APIs.

For example, a client might send:

POST /api/users
Content-Type: application/json
  

Request body:

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

The server could return:

{
  "id": 101,
  "name": "Adarsh",
  "email": "user@example.com",
  "created": true
}
  

JSON Request vs JSON Response

JSON Request JSON Response
Sent by client Returned by server
Contains input or requested data Contains result or requested information
Common with POST/PUT/PATCH Common for successful API operations

Content-Type: application/json

When an HTTP request contains a JSON body, the client commonly indicates the format using:

Content-Type: application/json
  

This helps the server understand how the request body should be interpreted.

JSON and JavaScript

JSON looks similar to JavaScript object syntax, but JSON and JavaScript objects are not exactly the same thing.

For example, JavaScript can contain:

const user = {
  name: "Adarsh",
  age: 25
};
  

Valid JSON would be represented as:

{
  "name": "Adarsh",
  "age": 25
}
  

JSON is a data interchange format, while a JavaScript object is an in-memory language value.

JSON.parse()

JavaScript provides JSON.parse() to convert a JSON string into a JavaScript value.

const jsonText = '{"name":"Adarsh","age":25}';

const user = JSON.parse(jsonText);

console.log(user.name);
  

After parsing, the application can access the data as a JavaScript object.

JSON.stringify()

JavaScript provides JSON.stringify() to convert a JavaScript value into a JSON string.

const user = {
  name: "Adarsh",
  age: 25
};

const jsonText = JSON.stringify(user);

console.log(jsonText);
  

This is commonly useful when preparing data for transmission or storage.

JSON With Fetch API

Modern browsers provide the Fetch API for HTTP communication.

For example:

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

The response.json() method reads the response body and parses JSON.

JSON in Python

Python also provides built-in JSON support through its json module.

Example:

import json

data = '{"name": "Adarsh", "age": 25}'

user = json.loads(data)

print(user["name"])
  

Python can also convert dictionaries into JSON text.

import json

user = {
    "name": "Adarsh",
    "age": 25
}

json_text = json.dumps(user)

print(json_text)
  

JSON in PHP

PHP provides functions such as json_encode() and json_decode().

Example:

<?php

$user = [
    "name" => "Adarsh",
    "age" => 25
];

echo json_encode($user);

?>
  

This can produce JSON such as:

{"name":"Adarsh","age":25}
  

JSON vs XML

Before JSON became widely popular in web development, XML was commonly used for structured data exchange.

Compare the same information in both formats.

JSON

{
  "name": "Adarsh",
  "age": 25
}
  

XML

<user>
  <name>Adarsh</name>
  <age>25</age>
</user>
  

Both can represent structured data. The choice depends on application requirements, existing systems, tooling, and API design.

JSON vs XML Comparison

JSON XML
Compact syntax Tag-based syntax
Common in modern web APIs Widely used in many existing enterprise and document-oriented systems
Native data structures for objects and arrays Uses elements and attributes
Generally straightforward for web developers Can support rich document structures and established XML technologies

Can JSON Store Functions?

No. Standard JSON does not have a function data type.

For example, this JavaScript object contains a function:

{
  name: "Adarsh",
  greet: function() {
    console.log("Hello");
  }
}
  

This cannot be represented as standard JSON in the same way.

Can JSON Store Dates?

JSON does not have a dedicated date type.

Applications commonly represent dates as strings, often using an agreed format such as an ISO-style timestamp.

{
  "createdAt": "2026-09-25T10:30:00Z"
}
  

The receiving application must interpret the string according to the API's documented rules.

Common JSON Mistakes

1. Using Single Quotes

This is not valid standard JSON:

{'name': 'Adarsh'}
  

Use double quotes:

{"name": "Adarsh"}
  

2. Trailing Commas

Do not add a comma after the final property or array element.

3. Incorrect Boolean Values

Use:

true
false
  

4. Missing Quotes Around Keys

Standard JSON requires object member names to be strings.

5. Missing Commas

Separate neighboring object properties or array values correctly.

6. Invalid Escape Sequences

Special characters inside strings must follow JSON's escaping rules.

How to Validate JSON

Because JSON syntax is strict, even a small formatting mistake can make a document invalid.

You can validate JSON using:

  • Code editors
  • Browser developer tools
  • Programming-language JSON parsers
  • Dedicated JSON validation tools
  • API testing tools

For applications, using the parser provided by your programming environment is often a reliable way to detect malformed JSON.

JSON Schema

JSON itself describes the structure of data, but it does not by itself define all the business rules an application might require.

JSON Schema is a separate specification that can describe expected JSON structure and constraints.

For example, a schema could specify that:

  • name must be a string
  • age must be a number
  • email should follow a defined format
  • id is required

This can help teams validate API payloads and communicate data contracts.

JSON and Databases

Applications frequently convert database records into JSON before returning them through APIs.

Database
   |
   v
Backend
   |
Convert Data
   |
   v
JSON Response
   |
   v
Frontend
  

A backend might query a relational or NoSQL database, transform the result, and return JSON to the frontend.

JSON in Full-Stack Development

JSON is especially important in full-stack applications.

A typical flow could be:

React / Frontend
       |
       | JSON Request
       v
REST API
       |
       v
Node.js / PHP / Python / Java
       |
       v
Database
       |
       v
JSON Response
       |
       v
Frontend UI
  

This is why understanding JSON is extremely useful for web developers.

JSON Security Considerations

JSON is a data format, not a security mechanism.

An API that uses JSON still requires appropriate security controls.

Developers should consider:

  • Input validation
  • Authentication
  • Authorization
  • HTTPS
  • Output handling
  • Payload size limits
  • Error handling
  • Protection of sensitive information

Never assume that JSON received from a client is trustworthy simply because it follows valid JSON syntax.

JSON and API Design

Good API design requires more than choosing JSON.

A well-designed API should clearly define:

  • Available endpoints
  • Request structure
  • Response structure
  • Authentication requirements
  • Validation rules
  • Error responses
  • Pagination behavior
  • Rate limits

Consistency is particularly important when many clients depend on the API.

Practical JSON Example: Product API

Suppose an online store returns a product:

{
  "id": 501,
  "name": "Mechanical Keyboard",
  "price": 2499,
  "currency": "INR",
  "available": true,
  "tags": [
    "keyboard",
    "mechanical",
    "gaming"
  ]
}
  

This response can easily be consumed by a website or mobile application.

Practical JSON Example: Blog API

{
  "id": 10,
  "title": "What Is JSON?",
  "author": {
    "id": 5,
    "name": "Adarsh"
  },
  "tags": [
    "JSON",
    "API",
    "Programming"
  ],
  "published": true
}
  

Notice how JSON can represent relationships and nested information in a readable structure.

How to Learn JSON

Beginners can learn JSON quickly by practicing the following:

  1. Learn key-value pairs.
  2. Learn JSON objects.
  3. Learn JSON arrays.
  4. Practice strings, numbers, booleans, and null.
  5. Practice nested objects.
  6. Practice arrays of objects.
  7. Read real API responses.
  8. Use JSON with JavaScript or Python.
  9. Build a small REST API.
  10. Validate and test JSON payloads.

JSON Practice Example

Try creating JSON for a student with:

  • Student ID
  • Name
  • Email
  • Course
  • Three subjects
  • Address
  • Whether the student is active

A possible answer is:

{
  "studentId": 101,
  "name": "Rahul",
  "email": "rahul@example.com",
  "course": "MCA",
  "subjects": [
    "DBMS",
    "Computer Networks",
    "Programming"
  ],
  "address": {
    "city": "Prayagraj",
    "state": "Uttar Pradesh"
  },
  "active": true
}
  

Frequently Asked Questions

```

What is JSON in simple words?

JSON is a text-based format used to represent structured data so that software systems can exchange and process information.

What does JSON stand for?

JSON stands for JavaScript Object Notation.

Is JSON a programming language?

No. JSON is a data interchange format.

Is JSON only used with JavaScript?

No. Many programming languages can parse and generate JSON.

What are the main JSON data types?

JSON supports strings, numbers, objects, arrays, booleans, and null.

What is the difference between JSON object and JSON array?

A JSON object contains key-value pairs and uses curly braces, while an array contains an ordered collection of values and uses square brackets.

Why is JSON used in APIs?

JSON provides a widely supported and relatively compact way to represent structured request and response data.

Can JSON contain functions?

No. Standard JSON does not have a function data type.

Can JSON contain dates?

JSON has no dedicated date type. Applications commonly represent dates as strings using an agreed format.

What is JSON.parse()?

In JavaScript, JSON.parse() converts a JSON string into a JavaScript value.

What is JSON.stringify()?

In JavaScript, JSON.stringify() converts a JavaScript value into a JSON string.

Is JSON secure?

JSON is only a data format. Security depends on how the application validates, authenticates, authorizes, transports, stores, and processes the data.

```

Final Thoughts

JSON is one of the most important formats to understand if you want to learn web development, APIs, backend programming, mobile development, or full-stack development.

The core concepts are simple: objects, arrays, keys, values, strings, numbers, booleans, null, and nested structures.

Once you understand those concepts, you will be able to read API responses, send data to backend servers, work with JavaScript's JSON functions, and communicate between different software systems much more comfortably.

CodeWithAV JSON Learning Path:

JSON Syntax → Objects → Arrays → Data Types → Nested JSON → API Requests → API Responses → JSON.parse() → JSON.stringify() → JSON Schema → Real API Projects.

Related Articles on CodeWithAV

What Is an API? Complete Beginner Guide

REST API Explained With Examples

What Is Cloud Computing?

What Is the Internet and How Does It Work?

Explore More Web Development Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

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

REST API Explained With Examples: Complete Beginner Guide

REST APIs are one of the most common ways modern web applications communicate with backend systems.

When a frontend application loads user information, creates an order, updates a profile, or deletes a task, it may communicate with a backend through a REST-style API.

For beginners, REST can initially seem complicated because it involves terms such as resources, endpoints, HTTP methods, statelessness, JSON, status codes, authentication, and CRUD operations.

This guide explains REST APIs step by step with simple examples so that you can understand the concepts and start building your own APIs.

Simple Definition: A REST API is a web API designed according to principles of the REST architectural style, typically using HTTP methods to interact with resources.

What Does REST Stand For?

REST stands for Representational State Transfer.

REST was introduced as an architectural style for designing networked systems. It is not a programming language, framework, or protocol.

REST APIs commonly use the existing HTTP protocol to expose and manipulate resources.

What Is a REST API?

A REST API provides an interface that allows clients to communicate with server-side resources using HTTP.

The client can be:

  • A web browser
  • A React application
  • A mobile application
  • A desktop application
  • Another backend service
  • A command-line program

The server may contain:

  • Business logic
  • Databases
  • Authentication systems
  • File storage
  • External service integrations
Client
  |
  | HTTP Request
  v
REST API
  |
  v
Application Logic
  |
  v
Database
  |
  v
REST API
  |
  | HTTP Response
  v
Client
  

What Is a Resource in REST?

A resource is an important concept in REST.

A resource can represent something that the application manages, such as:

  • Users
  • Products
  • Orders
  • Students
  • Courses
  • Blog posts
  • Comments
  • Tasks

For example, in a student management system, students could be a resource.

An endpoint might be:

/api/students
  

A specific student could be identified by:

/api/students/101
  

REST API Endpoint Examples

Suppose we are building an online store.

Possible resource endpoints could be:

/api/products
/api/products/25
/api/users
/api/users/15
/api/orders
/api/orders/500
  

The URL identifies the resource being accessed.

HTTP Methods in REST APIs

REST APIs commonly use HTTP methods to indicate what operation the client wants to perform.

GET

GET is generally used to retrieve a resource.

GET /api/products
  

This could return a collection of products.

To retrieve one product:

GET /api/products/25
  

POST

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

POST /api/products
  

The request body might contain:

{
  "name": "Wireless Keyboard",
  "price": 1499
}
  

PUT

PUT is commonly used to replace the representation of a resource.

PUT /api/products/25
  

A complete replacement representation might look like:

{
  "name": "Mechanical Keyboard",
  "price": 2499
}
  

PATCH

PATCH is commonly used when only part of a resource needs to be modified.

PATCH /api/products/25
  

The client may send only the field that needs to change:

{
  "price": 2299
}
  

DELETE

DELETE is generally used to remove a resource.

DELETE /api/products/25
  

REST and CRUD Operations

REST APIs are frequently designed around CRUD operations.

CRUD stands for:

  • Create
  • Read
  • Update
  • Delete
CRUD HTTP Method Example
Create POST POST /api/users
Read GET GET /api/users/15
Update PUT/PATCH PATCH /api/users/15
Delete DELETE DELETE /api/users/15

REST API Example: Student Management System

Let's design a small REST API for students.

Get All Students

GET /api/students
  

Possible response:

[
  {
    "id": 1,
    "name": "Rahul",
    "course": "MCA"
  },
  {
    "id": 2,
    "name": "Anita",
    "course": "BCA"
  }
]
  

Get One Student

GET /api/students/1
  

Create a Student

POST /api/students
  

Request body:

{
  "name": "Aman",
  "course": "MCA"
}
  

Update a Student

PATCH /api/students/1
  

Request body:

{
  "course": "MCA 2nd Year"
}
  

Delete a Student

DELETE /api/students/1
  

What Is Statelessness in REST?

Statelessness is one of the important REST constraints.

In a stateless interaction, each request contains the information needed by the server to understand and process that request. The server does not rely on storing client session state between requests as part of the REST interaction.

For example, an authenticated API request might contain a token:

Authorization: Bearer YOUR_ACCESS_TOKEN
  

The server can use the supplied credential to identify and authorize the request according to its authentication system.

Why Is Statelessness Useful?

Stateless APIs can make horizontal scaling easier because requests do not necessarily need to be routed back to one specific application server to recover local session state.

However, real systems may use supporting infrastructure such as shared session stores, caches, databases, or gateways. Statelessness describes how the API interaction is designed, not a promise that no state exists anywhere in the entire application.

JSON in REST APIs

JSON is a common format for REST API requests and responses.

Example response:

{
  "id": 101,
  "name": "Adarsh",
  "role": "Developer",
  "skills": [
    "JavaScript",
    "Python",
    "SQL"
  ]
}
  

The server can generate this response and the frontend can parse it into application data.

HTTP Status Codes in REST APIs

REST APIs should use appropriate HTTP status codes to communicate the outcome of requests.

Status Common Meaning Typical Example
200 OK Successful GET or update response
201 Created New resource created
204 No Content Successful operation with no response body
400 Bad Request Invalid request data
401 Unauthorized Missing or invalid authentication
403 Forbidden Authenticated but not allowed
404 Not Found Resource does not exist
409 Conflict Request conflicts with current resource state
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Unexpected server-side failure

What Are REST API Headers?

HTTP headers provide metadata about requests and responses.

Common examples include:

Content-Type: application/json
Accept: application/json
Authorization: Bearer YOUR_ACCESS_TOKEN
  

Content-Type tells the server what format the request body uses.

Accept can indicate the response formats the client can process.

Authorization can carry authentication credentials when the API's security design uses them.

Path Parameters vs Query Parameters

Path Parameters

Path parameters identify a specific resource or part of a resource path.

GET /api/products/25
  

Here, 25 can identify the product.

Query Parameters

Query parameters are useful for filtering, searching, sorting, and pagination.

GET /api/products?category=laptop&page=2
  

REST API Pagination

Returning thousands or millions of records in a single API response can be inefficient.

APIs commonly provide pagination.

For example:

GET /api/products?page=1&limit=20
  

This could request a particular page containing a limited number of products.

The exact pagination design depends on the API.

REST API Filtering and Searching

Query parameters can also be used to filter resources.

GET /api/products?category=phones
GET /api/products?minPrice=10000&maxPrice=50000
GET /api/users?role=admin
  

A well-designed API should document supported query parameters and their expected values.

REST API Authentication

Many REST APIs require clients to authenticate before accessing protected resources.

Common approaches include:

  • API keys
  • Bearer tokens
  • OAuth-based flows
  • Session-based systems
  • Other token-based authentication mechanisms

A protected request could look like:

GET /api/profile

Authorization: Bearer YOUR_ACCESS_TOKEN
  

Authentication vs Authorization

These two concepts are related but different.

Authentication asks: "Who are you?"

Authorization asks: "What are you allowed to do?"

For example, a user might successfully authenticate but still receive a 403 Forbidden response when attempting an administrative operation without the required permission.

REST API Security Basics

REST APIs should be designed with security in mind from the beginning.

Use HTTPS

HTTPS protects API traffic in transit.

Validate Input

Never assume client-provided data is trustworthy.

Implement Authorization

Do not rely only on authentication. Verify that the authenticated identity has permission for each sensitive operation.

Protect Secrets

Do not hard-code passwords, API keys, private tokens, or database credentials in public source code.

Rate Limit Sensitive Endpoints

Rate limiting can help control abusive or excessive traffic and can be particularly important for authentication and resource-intensive endpoints.

Return Safe Errors

Errors should help legitimate clients understand the problem without revealing unnecessary internal details.

REST API Versioning

APIs can evolve over time.

When incompatible changes are introduced, existing applications may need protection from unexpected behavior.

A common versioning approach is:

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

Versioning strategies differ. Some APIs use URLs, while others use headers or other mechanisms.

What Are REST API Error Responses?

A useful API should provide structured error responses instead of returning confusing or inconsistent messages.

For example:

{
  "error": "validation_error",
  "message": "Email address is invalid",
  "field": "email"
}
  

The exact structure can vary, but consistency makes APIs easier to consume.

REST API Naming Best Practices

Resource-oriented naming can make an API easier to understand.

Prefer clear resource names:

/api/users
/api/products
/api/orders
  

rather than unnecessarily action-heavy URLs such as:

/api/getAllUsers
/api/createProduct
/api/deleteOrder
  

The HTTP method already communicates the intended operation in many REST designs.

REST API Example With Node.js and Express

Here is a simple learning example using Express.js.

const express = require("express");

const app = express();

app.use(express.json());

app.get("/api/users", (req, res) => {
  res.json([
    {
      id: 1,
      name: "Adarsh"
    },
    {
      id: 2,
      name: "Rahul"
    }
  ]);
});

app.post("/api/users", (req, res) => {
  const { name } = req.body;

  res.status(201).json({
    message: "User created",
    name
  });
});

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

This is only a learning example. A production API would also need appropriate validation, authentication, authorization, persistent storage, error handling, logging, security controls, and testing.

Calling a REST API From JavaScript

A frontend application can use the Fetch API to call a REST endpoint.

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

The frontend receives the JSON response and can use the returned data to update the interface.

Testing REST APIs

Before connecting an API to a frontend, developers can test it independently.

API testing tools can help you:

  • Send GET requests
  • Send POST requests
  • Modify request headers
  • Send JSON bodies
  • Test authentication
  • Inspect responses
  • Test error conditions
  • Save reusable requests

Postman, curl, and automated testing frameworks are commonly used for API testing.

Testing With curl

For example, a GET request can be sent from a terminal:

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

A POST request could look like:

curl -X POST https://example.com/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Adarsh"}'
  

The exact command depends on the API and operating system.

REST API Architecture Example

                 Client
                   |
                   v
              REST API
                   |
              +----+----+
              |         |
              v         v
          Controller   Auth
              |
              v
        Business Logic
              |
              v
           Database
  

A larger production application may contain additional layers such as API gateways, caches, queues, background workers, external services, observability systems, and multiple backend services.

REST API vs SOAP API

REST SOAP
Architectural style Protocol
Commonly uses HTTP Can operate over multiple underlying transports
Often uses JSON, but other formats are possible Traditionally associated with XML messaging
Common in web and mobile APIs Often used in enterprise systems requiring SOAP features and contracts

REST API vs GraphQL

REST GraphQL
Usually exposes resource-oriented endpoints Often exposes a schema and query language
Uses HTTP methods heavily Clients commonly describe the fields they need
Often straightforward for standard CRUD APIs Can be useful when clients need flexible data selection

Common REST API Mistakes

  1. Using unclear or inconsistent endpoint names.
  2. Ignoring HTTP status codes.
  3. Returning inconsistent response structures.
  4. Skipping input validation.
  5. Checking authentication but not authorization.
  6. Exposing secrets in source code.
  7. Returning sensitive internal information in error messages.
  8. Ignoring rate limiting for sensitive endpoints.
  9. Changing API behavior without a migration strategy.
  10. Building an API without documentation and tests.

How to Build Your First REST API

Beginners can follow this practical sequence:

  1. Learn HTTP fundamentals.
  2. Understand request and response structure.
  3. Learn JSON.
  4. Learn GET, POST, PUT, PATCH, and DELETE.
  5. Understand endpoints and parameters.
  6. Learn CRUD.
  7. Build a small API with a backend framework.
  8. Connect a database.
  9. Add validation.
  10. Add authentication and authorization.
  11. Test the API.
  12. Document the endpoints.
  13. Deploy the application.

Beginner REST API Project Ideas

1. Todo API

Create, read, update, and delete tasks.

2. Student API

Manage student profiles, courses, and academic information.

3. Blog API

Manage posts, categories, comments, and authors.

4. Expense Tracker API

Create endpoints for recording and analyzing personal expenses.

5. Library Management API

Manage books, members, borrowing, and returns.

6. Authentication API

Build a learning project around registration, login, authentication, and role-based authorization.

Frequently Asked Questions

```

What is a REST API in simple words?

A REST API is a way for applications to communicate over HTTP using resource-oriented interfaces and standard HTTP methods.

What does REST stand for?

REST stands for Representational State Transfer.

Is REST a programming language?

No. REST is an architectural style for designing networked applications.

What is the difference between API and REST API?

API is a broad concept describing a software interface. REST API refers specifically to an API designed according to principles associated with REST.

What are the main REST API methods?

GET, POST, PUT, PATCH, and DELETE are commonly used in REST APIs.

What is CRUD in REST API?

CRUD means Create, Read, Update, and Delete. REST APIs commonly map these operations to HTTP methods.

Does every REST API use JSON?

No. REST does not require JSON. JSON is simply a very common representation format for modern web APIs.

What is a REST API endpoint?

An endpoint is a specific URL through which a client accesses a resource or operation exposed by an API.

Is REST API secure?

A REST API can be secure when it is correctly designed and implemented. Security requires appropriate authentication, authorization, transport protection, input validation, secret management, logging, and other controls.

Can beginners build REST APIs?

Yes. Beginners can start with a small CRUD API and gradually add databases, authentication, validation, testing, and deployment.

```

Final Thoughts

REST APIs provide a practical way for different software components to communicate over HTTP.

The most important concepts to understand are resources, endpoints, HTTP methods, requests, responses, JSON, status codes, CRUD, statelessness, authentication, authorization, and API security.

You do not need to memorize every REST concept before writing your first API. Build a small project, test each endpoint, inspect the requests and responses, and gradually add production-level features.

CodeWithAV REST API Learning Path:

HTTP → JSON → Resources → Endpoints → GET/POST → PUT/PATCH/DELETE → CRUD → Authentication → Authorization → Database → Testing → Documentation → Deployment.

Related Articles on CodeWithAV

What Is an API? Complete Beginner Guide

What Is JSON?

HTTP vs HTTPS Explained

HTTP Status Codes Every Developer Should Know

What Is Cloud Computing?

Explore More Web Development Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

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

Whenever a website displays weather information, a mobile application loads your profile, an online store processes a payment, or an application uses an AI model, there is often a system communicating with another system behind the scenes.

One of the most important technologies that makes this communication possible is an API.

API stands for Application Programming Interface. It provides a defined way for software systems to communicate with each other.

Simple Definition: An API is a set of rules and interfaces that allows one software system to request data or functionality from another software system.

In this beginner-friendly guide, you will learn what an API is, how an API request works, common HTTP methods, API responses, JSON, REST APIs, authentication, status codes, examples, and why APIs are essential for modern software development.

What Does API Mean?

An API is an interface through which software components communicate.

Instead of requiring one application to understand the internal implementation of another application, an API exposes a defined interface that tells clients:

  • What operations are available
  • What information can be requested
  • What data needs to be provided
  • How requests should be formatted
  • What responses look like
  • What authentication may be required

This allows different software systems to work together without exposing their entire internal implementation.

API Explained With a Restaurant Example

Imagine that you are sitting in a restaurant.

You do not normally walk into the kitchen and prepare your own food. Instead, you look at the menu, place an order, and receive the result.

In this analogy:

  • You = Client
  • Menu = API documentation
  • Waiter = API interface
  • Kitchen = Server or backend
  • Food = Response
Client
  |
  | Request
  v
+---------+
|   API   |
+---------+
  |
  | Request forwarded
  v
Backend / Database
  |
  | Result
  v
+---------+
|   API   |
+---------+
  |
  | Response
  v
Client
  

The API provides a controlled communication layer between the client and the backend.

Why Do We Need APIs?

Modern applications are rarely isolated systems.

A single application may need to communicate with:

  • A database
  • A payment service
  • An authentication system
  • A weather service
  • A mapping service
  • An email service
  • An AI service
  • A cloud storage service
  • Another internal application

APIs provide a structured way to connect these components.

Real-World API Examples

Weather Application

A weather application can send a request to a weather API and receive current or forecast information.

Payment Application

An e-commerce website can communicate with a payment provider through an API to initiate or verify a payment.

Maps

An application can use a mapping API to obtain map-related data or functionality without building an entire mapping platform from scratch.

Social Login

An application can integrate with an identity provider through APIs to support authentication flows.

AI Applications

An application can send input to an AI service through an API and receive generated output.

How Does an API Work?

A common web API workflow looks like this:

1. Client prepares request
          ↓
2. Client sends HTTP request
          ↓
3. API receives request
          ↓
4. API validates request
          ↓
5. Backend processes request
          ↓
6. Database or service may be accessed
          ↓
7. API creates response
          ↓
8. Client receives response
  

For example, a client might request information about a user.

GET /api/users/25
  

The server may return information such as:

{
  "id": 25,
  "name": "Rahul",
  "role": "Developer"
}
  

What Is an API Request?

An API request is a message sent by a client to an API.

A typical HTTP API request can contain:

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

What Is an API Response?

An API response is the information returned by the server after processing a request.

A response can contain:

  • Status code
  • Response headers
  • Response body

HTTP Methods Used in APIs

Web APIs commonly use HTTP methods to indicate the intended operation.

GET

GET is generally used to retrieve data.

GET /api/products
  

This could request a collection of products.

POST

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

POST /api/users
  

PUT

PUT is commonly used to replace a resource with a new representation.

PUT /api/users/25
  

PATCH

PATCH is commonly used to partially modify a resource.

PATCH /api/users/25
  

DELETE

DELETE is generally used to remove a resource.

DELETE /api/users/25
  

HTTP Methods at a Glance

Method Common Purpose Example
GET Retrieve data Get a list of users
POST Create or submit data Create a user
PUT Replace a resource Replace user details
PATCH Partially update a resource Update only a username
DELETE Delete a resource Delete a user

What Is an API Endpoint?

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

For example:

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

Each endpoint may represent a different resource or operation.

What Is a Base URL?

The base URL is the common starting portion of an API's endpoints.

For example:

https://api.example.com
  

An endpoint might then be:

https://api.example.com/users
  

What Are API Parameters?

Parameters allow clients to provide additional information to an API.

Path Parameters

A path parameter is included as part of the URL path.

GET /users/25
  

Here, 25 can identify a particular user.

Query Parameters

Query parameters are commonly added after a question mark.

GET /products?category=laptop&page=2
  

They can be used for filtering, searching, sorting, pagination, or other optional controls.

Request Body

A request body can contain data sent to an API, especially with methods such as POST, PUT, and PATCH.

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

What Is JSON?

JSON stands for JavaScript Object Notation. It is a commonly used text format for representing structured data in web APIs.

Example:

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

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

What Are HTTP Headers?

HTTP headers contain additional information about an HTTP request or response.

Examples include:

Content-Type: application/json
Accept: application/json
Authorization: Bearer YOUR_TOKEN
  

Headers can communicate information about the content type, authentication, caching, accepted response formats, and other request or response characteristics.

What Is API Authentication?

Some APIs are publicly accessible for particular operations, while others require authentication.

Authentication allows the API to identify the client or user making a request.

Common approaches include:

  • API keys
  • Bearer tokens
  • Session-based authentication
  • OAuth-based authorization flows
  • Other token-based mechanisms
Security Tip: Never publish private API keys, passwords, access tokens, or other secrets in public GitHub repositories, frontend source code, screenshots, or blog posts.

API Key Example

A service may require a client to send an API key with a request.

GET /api/weather

Authorization: YOUR_API_KEY
  

The exact header or parameter format depends on the API provider.

What Are HTTP Status Codes?

HTTP status codes communicate the result of an HTTP request.

Code Meaning
200 Request succeeded
201 Resource created
204 Success with no response body
400 Bad request
401 Authentication required or failed
403 Request is understood but not permitted
404 Resource not found
429 Too many requests
500 Internal server error

What Is REST API?

REST stands for Representational State Transfer.

REST is an architectural style used to design networked applications. APIs designed around REST principles are commonly called REST APIs.

A REST-style API typically exposes resources through URLs and uses standard HTTP methods to operate on them.

For example:

GET     /users
POST    /users
GET     /users/25
PUT     /users/25
PATCH   /users/25
DELETE  /users/25
  

REST API Example

Suppose an application manages products.

The API could use endpoints such as:

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

The client does not need to know how the database internally stores the product information. It interacts with the API according to its documented interface.

What Is an API Contract?

An API contract describes how clients should communicate with the API.

It can specify:

  • Available endpoints
  • HTTP methods
  • Required parameters
  • Request formats
  • Response formats
  • Authentication requirements
  • Error responses

A clear API contract helps frontend developers, backend developers, mobile developers, testers, and external consumers work with the same interface.

What Is API Documentation?

API documentation explains how developers can use an API.

Good API documentation generally includes:

  • Endpoint URLs
  • HTTP methods
  • Authentication instructions
  • Request examples
  • Response examples
  • Error codes
  • Parameter descriptions
  • Usage limits

Tools such as OpenAPI-based documentation systems can help teams describe and present APIs.

What Is an API Rate Limit?

A rate limit restricts how many requests a client can make within a particular period.

For example, an API could allow a particular client to make only a certain number of requests within a minute.

Rate limiting helps control resource usage and can reduce abuse or excessive traffic.

What Is API Versioning?

APIs may evolve over time.

Changing an existing API without considering existing clients can break applications that depend on the older behavior.

API versioning provides a way to manage incompatible changes.

One possible design is:

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

The exact versioning strategy depends on the API design and organizational requirements.

What Is an Internal API?

An internal API is designed primarily for communication between components within the same organization or system.

For example, an e-commerce platform may have separate services for:

  • Users
  • Orders
  • Payments
  • Inventory
  • Notifications

These services may communicate through internal APIs.

What Is a Public API?

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

Public APIs may require registration, API keys, authentication, rate limits, usage restrictions, or payment depending on the service.

What Is a Private API?

The term private API can refer to an API restricted to a particular organization, team, application, or environment.

Private APIs are commonly used to connect internal systems without making the interface publicly available.

API vs Library

API Library
Defines an interface for interaction Provides reusable code
Can connect separate systems Usually added directly to an application
May operate over a network Usually executes within the application environment

The term API is broader than web APIs. A programming library itself can expose an API that other code uses.

API vs Database

An API and database serve different purposes.

A database stores and organizes data, while an API provides an interface through which software can access or manipulate data and functionality.

Frontend
   |
   v
  API
   |
   v
Backend Logic
   |
   v
Database
  

In a well-designed application, clients commonly interact with the backend through an API rather than directly connecting to the database.

API and Frontend Development

A modern frontend application may communicate with a backend API to retrieve and modify application data.

For example, a JavaScript application can send an HTTP request:

fetch("/api/users")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });
  

The frontend receives the response and can use the data to update the user interface.

API and Backend Development

Backend developers build API endpoints that perform operations and return appropriate responses.

A simplified backend architecture might look like:

HTTP Request
     ↓
Router
     ↓
Controller
     ↓
Business Logic
     ↓
Database / External Service
     ↓
Response
  

This structure can vary significantly depending on the programming language and architecture.

Simple API Example Using Node.js

Here is a very small conceptual example using Express.js:

const express = require("express");

const app = express();

app.get("/api/hello", (req, res) => {
  res.json({
    message: "Hello from the API"
  });
});

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

A request to:

GET /api/hello
  

could produce a JSON response such as:

{
  "message": "Hello from the API"
}
  

API Testing

Developers and testers need to verify that APIs behave correctly.

Common API testing tasks include:

  • Testing different HTTP methods
  • Checking status codes
  • Testing valid and invalid inputs
  • Checking authentication
  • Testing error handling
  • Testing response structure
  • Testing rate limits
  • Checking authorization boundaries

Tools such as Postman, command-line HTTP clients, automated testing frameworks, and browser developer tools can help with API testing.

API Security Basics

APIs often expose valuable application functionality, so security is an essential part of API development.

Authentication

Verify the identity of clients or users where required.

Authorization

Check whether an authenticated user has permission to perform a specific action.

Input Validation

Validate incoming data instead of trusting client input.

HTTPS

Use encrypted transport for sensitive API communication.

Rate Limiting

Limit excessive requests where appropriate.

Secret Management

Keep API keys, passwords, and tokens out of source code repositories and client-side code when they are supposed to remain secret.

Error Handling

Return useful errors without exposing unnecessary internal details.

Common API Mistakes

  1. Using unclear endpoint names.
  2. Returning inconsistent response formats.
  3. Ignoring authentication and authorization.
  4. Trusting user input.
  5. Exposing sensitive information in errors.
  6. Hard-coding secrets.
  7. Ignoring rate limiting where it is needed.
  8. Failing to document endpoints.
  9. Changing APIs without considering existing clients.

API Architecture Example

                Mobile App
                    |
                    |
Web App -------- API Gateway -------- External Services
                    |
                    v
                 Backend
              /     |     \
             /      |      \
            v       v       v
         Users    Orders   Payments
            \       |       /
             \      |      /
                  Database
  

Large production systems can be significantly more complicated, but this model helps beginners understand the role of APIs as a communication layer.

APIs in Modern Software Development

APIs are used across many areas of modern software engineering:

  • Web applications
  • Mobile applications
  • Cloud computing
  • Microservices
  • Artificial intelligence
  • Payment systems
  • Social platforms
  • IoT applications
  • DevOps automation
  • Enterprise software

How to Learn APIs as a Beginner

A practical API learning path can be:

  1. Learn basic HTTP.
  2. Understand URLs, headers, methods, and status codes.
  3. Learn JSON.
  4. Use a public API.
  5. Practice GET and POST requests.
  6. Learn authentication concepts.
  7. Practice with Postman.
  8. Build a small REST API.
  9. Connect a frontend application to your API.
  10. Add validation, authentication, authorization, logging, and error handling.

Beginner API Projects

1. Weather Dashboard

Build a frontend application that consumes a weather API and displays selected weather information.

2. Notes API

Create an API that lets users create, read, update, and delete notes.

3. Todo API

Build a CRUD API for managing tasks.

4. Student Management API

Create endpoints for students, courses, marks, and attendance.

5. Blog API

Create an API for posts, categories, comments, and users.

6. Authentication API

Build a small learning project involving registration, login, password hashing, authentication, and authorization.

Frequently Asked Questions

```

What is an API in simple words?

An API is an interface that allows one software system to communicate with another software system according to defined rules.

What does API stand for?

API stands for Application Programming Interface.

What is an API endpoint?

An endpoint is a specific URL or interface location through which an API provides a resource or operation.

What is a REST API?

A REST API is an API designed using principles associated with the REST architectural style, commonly using HTTP methods and resource-oriented URLs.

What is JSON in an API?

JSON is a common text-based format used to represent structured data exchanged by web APIs.

What is the difference between API and REST API?

API is a broad concept describing a software interface. REST API refers to an API designed around the REST architectural style.

What is an API key?

An API key is a credential used by some services to identify or authenticate API clients. The exact security model depends on the service.

Are all APIs web APIs?

No. APIs can exist within programming libraries, operating systems, databases, software frameworks, and many other environments. Web APIs are only one category.

Do APIs always use JSON?

No. APIs can use different data formats. JSON is simply very common in modern web APIs.

Can a beginner build an API?

Yes. Beginners can build small APIs using frameworks such as Express.js, FastAPI, Flask, Spring Boot, ASP.NET Core, Laravel, and others.

```

Final Thoughts

APIs are one of the fundamental building blocks of modern software.

Whenever different applications or components need to communicate, an API can provide a structured interface between them.

For beginners, focus first on understanding HTTP requests, endpoints, methods, headers, JSON, status codes, authentication, and API security. Once those concepts become familiar, building REST APIs becomes much easier.

CodeWithAV API Learning Path:

HTTP Basics → JSON → REST Concepts → API Requests → API Responses → Authentication → Postman → Build Your Own API → Connect Frontend → Secure and Deploy.

Related Articles on CodeWithAV

What Is an API? Complete Beginner Guide

REST API Tutorial for Beginners

What Is JSON?

HTTP vs HTTPS Explained

HTTP Status Codes Every Developer Should Know

Explore More Programming and Web Development Guides

Disclosure: Some links on CodeWithAV may be affiliate links. If you purchase a product or service through an affiliate link, we may earn a commission at no additional cost to you. We aim to recommend products and services based on their relevance to our readers.

CodeWithAV — Learn, Discover & Build.

Adarsh verma

Adarsh verma

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