Skip to main content

Understanding REST API

What Is an API?

An API (Application Programming Interface) is a set of rules and conventions that allows different software systems to communicate with each other. In the context of web applications, APIs let clients (like browsers or mobile apps) interact with backend servers to retrieve, send, update, or delete data.


What Is REST?

REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful APIs use HTTP methods to perform actions on resources, typically represented as URLs.

Why REST?

  • Stateless Communication
    Each REST request contains all the information needed to complete the request. The server doesn’t store client context between requests, which simplifies scaling and reduces memory overhead on the server.

  • Easy to Cache
    REST relies on HTTP, which supports built-in caching mechanisms using headers like Cache-Control, ETag, and Last-Modified. This improves performance and reduces server load by allowing frequently requested resources to be served from cache.

  • Works Over Standard HTTP
    REST uses HTTP methods like GET, POST, PUT, and DELETE — the same protocol your browser uses. This makes it easy to test (e.g., using Postman or curl), deploy, and integrate over the web without custom protocols.

  • Language-Agnostic and Scalable
    REST APIs use plain text (typically JSON), which is supported across all major programming languages. This makes REST ideal for building distributed systems, microservices, and cross-platform apps that need to scale horizontally and communicate over the network.


RESTful Concepts


Common REST Verbs

VerbPurposeExample
GETRetrieve dataGET /outlets
POSTCreate new dataPOST /outlets
PUTUpdate existing dataPUT /outlets/123
DELETEDelete dataDELETE /outlets/123

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate.

✨ Brief History

  • Developed by Douglas Crockford in early 2000s
  • Became widely popular with the rise of AJAX and dynamic web applications
  • Now supported by nearly every language

📐 JSON Syntax

{
"name": "Taco Town",
"location": "San Diego",
"rating": 4.7
}
  • Data is in key-value pairs
  • Keys are strings
  • Values can be strings, numbers, booleans, arrays, or other objects

🍔 Example REST API: Retrieve Food Outlets

GET /api/outlets

Returns a list of food outlets from the database.

Sample Response:

[
{
"id": 1,
"name": "Taco Town",
"location": "San Diego",
"rating": 4.7
},
{
"id": 2,
"name": "Pizza Palace",
"location": "New York",
"rating": 4.3
}
]

Fetching Data in JavaScript

Using .then() Promises

fetch("https://example.com/api/outlets")
.then(response => response.json())
.then(data => {
console.log("Food Outlets:", data);
})
.catch(error => {
console.error("Error fetching data:", error);
});

Keywords

  • fetch(): Initiates an HTTP request and returns a Promise.

  • .then(): Executes the callback after the promise resolves.

  • .catch(): Catches any errors that occur in the promise chain.

Fetch Data in JavaScript (Using async/await)

async function fetchOutlets() {
try {
const response = await fetch("https://example.com/api/outlets");
const data = await response.json();
console.log("Food Outlets:", data);
} catch (error) {
console.error("Error fetching data:", error);
}
}

fetchOutlets();

This code sends a GET request to the API and logs the list of outlets.

What Is await?

The await keyword is used inside an async function to pause the execution of that function until the awaited Promise is settled (resolved or rejected).

The Paradigm Behind await:

  • It allows asynchronous code to look and behave like synchronous code, making it easier to read and maintain.
  • Execution is paused at each await until the result is available — just like saying: “I’ll wait here until this finishes.”
  • Unlike then() chains, await works well with try/catch blocks for clean error handling.

Conceptual Differences

Aspect.then() (Function 1)async/await (Function 2)
StyleChained PromisesSynchronous-looking async code
ReadabilityHarder to read when deeply nestedMore readable for sequential steps
Error HandlingRequires .catch() at the endUses try/catch block, like synchronous code
Syntactic SugarNo keywords, pure Promise chainingRequires async and await keywords
Best ForShort chains or dynamic piping of promisesComplex flows with multiple awaits or error-handling branches

Summary

  • REST is a style of web API architecture based on resources and HTTP methods.
  • JSON is the standard data format for communication between frontend and backend.
  • You can use fetch() in JavaScript to interact with REST APIs easily.

REST API: Retrieve TV Shows (Paginated)

GET /api/tv-shows

  • Retrieves a list of TV shows with optional pagination parameters.

Query Parameters

ParameterTypeRequiredDescription
pageintegerNoThe page number to retrieve (e.g., 1, 2, etc.)
limitintegerNoThe number of items per page (default is 10)
offsetintegerNoThe number of items to skip (used in offset-based pagination)

GET /api/tv-shows?page=2&limit=5

  • This request asks for page 2, returning 5 shows per page.

Or alternatively:

GET /api/tv-shows?offset=10&limit=5

  • This skips the first 10 records and returns the next 5.

✅ Example Response

{
"page": 2,
"limit": 5,
"total": 23,
"tvShows": [
{
"id": 6,
"title": "Stranger Things",
"genre": "Sci-Fi",
"rating": 8.7
},
{
"id": 7,
"title": "Breaking Bad",
"genre": "Drama",
"rating": 9.5
},
...
]
}

REST API: Retrieve Football Club Data

GET /api/clubs

  • This endpoint retrieves a list of football clubs from the database. Supports optional filtering and sorting.

🔍 Query Parameters

ParameterTypeRequiredDescription
leaguestringNoFilter clubs by league (e.g., Premier League)
countrystringNoFilter clubs by country (e.g., England)
sortBystringNoSort results by field (e.g., name, rank)
orderstringNoSorting order: asc or desc
pageintegerNoPage number for pagination
limitintegerNoNumber of results per page

GET /api/clubs?league=La%20Liga&country=Spain&sortBy=rank&order=asc&page=1&limit=10

  • This fetches La Liga clubs from Spain, sorted by rank ascending, returning the first 10 clubs.

Response

{
"page": 1,
"limit": 10,
"total": 20,
"clubs": [
{
"id": 1,
"name": "Real Madrid",
"country": "Spain",
"league": "La Liga",
"rank": 1
},
{
"id": 2,
"name": "FC Barcelona",
"country": "Spain",
"league": "La Liga",
"rank": 2
}
// ...more clubs
]
}

**Notes**
- If no query parameters are provided, the API returns a default list of clubs.
- Sorting and filtering help tailor results for analytics, dashboards, and search features.

## REST API: Get Country Calling Codes

**GET /api/countries/{countryName}/calling-codes**

- This endpoint retrieves the calling code(s) for a given country.

---

**Example:**

```GET /api/countries/India/calling-codes```

**Response**

```json
{
"country": "India",
"callingCodes": ["+91"]
}


**GET /api/calling-codes/{code}/country**

- Retrieves country information associated with a given calling code.

**Example**

```GET /api/calling-codes/+91/country```

**Response**

✅ Example Response

{
"callingCode": "+91",
"country": "India",
"region": "Asia",
"isoCode": "IN"
}

🔍 Example Request