JavaScript: APIs (In-Depth)

An API (Application Programming Interface) is a set of rules and endpoints that lets programs or scripts communicate with each other. In web development, APIs usually mean "web APIs"—services you can call over the network to send or receive data.

Calling APIs from JavaScript

Use fetch() (modern) or XMLHttpRequest (legacy) to make HTTP requests from JS.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data));
    
// Output:
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }

How fetch() Works

fetch("https://api.example.com/data")
  .then(res => res.json())
  .then(data => {/* use data */});
    

Common API Request Types

Sending Data to an API

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

Best Practices

Practice: Try calling a public API and displaying the result in your HTML page using fetch and DOM manipulation.