What is an API?

Why APIs Matter

APIs (Application Programming Interfaces) are the bridges that allow your JavaScript code to interact with external services, databases, or other applications. In web development, they enable dynamic content loading without full page reloads—think fetching user data, posting forms, or displaying real-time updates.

Definition

An API is a set of rules and protocols that allows different software components to communicate. In JavaScript, we often deal with RESTful APIs (Representational State Transfer), which use standard HTTP methods to perform CRUD operations (Create, Read, Update, Delete) on resources.

Syntax and Structure

APIs typically expose endpoints (URLs) like https://api.example.com/users. You send HTTP requests to these endpoints and receive responses, usually in JSON format.

Basic Syntax (Using Fetch API)

fetch('https://api.example.com/endpoint')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Types of APIs

Example: Fetching Data from a Public API

Below is an interactive example using the Dog CEO API to fetch random dog images. This demonstrates asynchronous JavaScript with Promises and Fetch.

Random Dog Image


JSON: The Language of APIs

JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read and machines to parse. It's the de facto standard for API responses in JavaScript.

Syntax

JSON uses key-value pairs, similar to JavaScript objects, but with stricter rules: double quotes for strings, no trailing commas, no functions.

Valid JSON Syntax

{
  "name": "John Doe",
  "age": 30,
  "hobbies": ["reading", "coding"],
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  }
}

Example

Suppose an API returns user data:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

In JavaScript, you can parse it with response.json() and access like data.title.

JSON.stringify() and JSON.parse()

JSON.stringify(obj) converts a JavaScript object to a JSON string (for sending data via POST). JSON.parse(str) does the reverse.

Using stringify()

const user = { name: 'Alice', age: 25 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Alice","age":25}'

const parsed = JSON.parse(jsonString);
console.log(parsed.name); // 'Alice'

HTTP Methods: GET, POST, DELETE

APIs use HTTP methods to define actions. These are the building blocks of CRUD operations.

GET: Retrieve Data

Used to fetch resources. Idempotent (safe to repeat). No body in request.

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data));

POST: Create Data

Sends data to create a new resource. Includes a request body (usually JSON).

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'New Post', body: 'Content', userId: 1 })
})
.then(response => response.json())
.then(data => console.log(data));

DELETE: Remove Data

Deletes a resource. Idempotent.

fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'DELETE' })
  .then(response => console.log('Deleted:', response.ok));

Pro Tip: Always handle errors with .catch() or try-catch in async/await. Check response status with response.ok.