5 Connection: APIs as Business Integration
5.1 The Concept First
So far, everything you’ve built lives in isolation. Your HTML, CSS, and JavaScript create an experience, but that experience is self-contained—it doesn’t connect to anything beyond itself.
Real business applications are different. They display live weather data. They process payments. They show inventory levels. They sync with customer databases. They pull content from external services. How?
APIs—Application Programming Interfaces.
An API is a defined way for two systems to communicate. When your JavaScript asks a weather service “What’s the temperature in Perth?”, it’s using an API. When a customer’s payment details go to Stripe for processing, that’s an API. When your portfolio site pulls your latest GitHub projects, that’s an API.
APIs transform your website from a standalone document into a connected application that interacts with the wider world.
5.2 Understanding Through Contracts
Think of an API as a contract between two parties. Like any good contract, it specifies:
- What you can ask for (the endpoints)
- How to ask (the request format)
- What you’ll receive (the response format)
- What happens if something goes wrong (error handling)
Imagine a restaurant:
- The menu lists what you can order (available endpoints)
- You place an order in a specific way—verbally to a waiter, on a printed slip (request format)
- The kitchen prepares your food and the waiter delivers it (response)
- If something’s unavailable, they tell you (error response)
You don’t need to know how the kitchen works. You just need to know how to order and what to expect. That’s the power of a well-defined interface.
When working with any API, first understand the contract: What can I request? What format does it expect? What will I receive? What errors might occur? Read the documentation before writing code.
5.3 Discovering Connection with Your AI Partner
Exploration 1: How APIs Work
Let’s build understanding before we see code:
Ask your AI:
Explain REST APIs using a library system analogy. The library has
books (resources). How would a REST API let someone check what
books exist, borrow a book, return a book, and add new books?
This should reveal the core pattern: APIs expose resources (data) and let you perform operations on them. The operations typically map to HTTP methods: GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
Continue the conversation:
What's the difference between GET and POST requests? Why would you
use one versus the other?
Exploration 2: Data Formats
APIs need a common language for data. That language is usually JSON.
Ask your AI:
Why is JSON the standard format for web API data? What problem does
it solve, and what did people use before JSON?
JSON (JavaScript Object Notation) is readable by humans and easily parsed by machines. It’s become the universal format for web data exchange.
Continue the conversation:
Show me what a JSON response might look like for a product catalog
with three items. Each item has a name, price, description, and
whether it's in stock.
Exploration 3: What Can Go Wrong?
Network requests fail. Servers go down. Data doesn’t match expectations. Professional applications handle these gracefully.
Ask your AI:
What can go wrong when calling an API? List the different types of
failures and explain what each HTTP status code range (2xx, 4xx, 5xx)
means.
Understanding failure modes is essential. Your code must handle them or your users will see cryptic errors—or worse, a completely broken page.
Continue the conversation:
How should a professional application respond to each type of failure?
What should the user see?
5.4 From Concept to Code
Let’s build your API understanding progressively, from fetching data to handling complex scenarios.
The Fetch API
JavaScript’s fetch() function makes HTTP requests:
fetch('https://api.example.com/products')
.then(response => response.json())
.then(data => {
console.log(data);
});This fetches data from a URL, converts the response to JSON, and logs it. But what’s with all those .then() calls?
Understanding Asynchronous Code
API requests take time. The server might be across the world. Your code can’t just wait—it would freeze the entire page.
JavaScript handles this with asynchronous code. Instead of stopping and waiting, it says “start this request, and when it’s done, run this code.”
The .then() pattern is called a Promise. But modern JavaScript has a cleaner syntax: async/await.
Async/Await: Readable Asynchronous Code
async function loadProducts() {
const response = await fetch('https://api.example.com/products');
const data = await response.json();
console.log(data);
}
loadProducts();await pauses the function (not the whole page) until the operation completes. The async keyword marks functions that use await.
This reads more naturally: “Fetch the URL. Wait. Parse the JSON. Wait. Log the data.”
A Complete Example: Displaying API Data
Let’s fetch real data and display it:
<section id="products">
<h2>Our Products</h2>
<div id="product-list">Loading...</div>
</section>async function displayProducts() {
const container = document.querySelector('#product-list');
try {
const response = await fetch('https://fakestoreapi.com/products?limit=3');
const products = await response.json();
// Clear loading message
container.innerHTML = '';
// Create HTML for each product
products.forEach(product => {
const productCard = document.createElement('div');
productCard.classList.add('product-card');
productCard.innerHTML = `
<h3>${product.title}</h3>
<p>$${product.price}</p>
`;
container.appendChild(productCard);
});
} catch (error) {
container.innerHTML = '<p>Sorry, products could not be loaded.</p>';
console.error('Fetch failed:', error);
}
}
displayProducts();Key elements:
- Show a loading state initially
- Fetch data with
await - Parse JSON with
await - Create DOM elements for each item
- Handle errors with
try/catch
Ask your AI:
Walk me through this code step by step. What does forEach do?
What does createElement do? What happens if the fetch fails?
Working with JSON Data
JSON data looks like JavaScript objects:
{
"id": 1,
"title": "Product Name",
"price": 29.99,
"category": "electronics",
"inStock": true,
"tags": ["featured", "sale"]
}Accessing data uses dot notation or brackets:
const product = await response.json();
console.log(product.title); // "Product Name"
console.log(product.price); // 29.99
console.log(product.tags[0]); // "featured"
console.log(product['category']); // "electronics"For arrays of items:
const products = await response.json();
products.forEach(product => {
console.log(product.title);
});
// Or find specific items
const expensive = products.filter(p => p.price > 50);
const firstElectronic = products.find(p => p.category === 'electronics');Error Handling in Depth
Robust applications handle multiple failure scenarios:
async function loadData() {
try {
const response = await fetch('https://api.example.com/data');
// Check if the response was successful
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error.name === 'TypeError') {
// Network failure - couldn't reach the server
console.error('Network error:', error);
return { error: 'Unable to connect. Please check your internet.' };
} else {
// Other error (including our HTTP error)
console.error('Fetch error:', error);
return { error: 'Something went wrong. Please try again.' };
}
}
}response.ok
A fetch() that reaches the server won’t throw an error even if the server returns a 404 or 500 status. You must check response.ok to detect these failures.
Loading States
Users should never see a blank screen while waiting:
async function loadWithStatus() {
const container = document.querySelector('#content');
const loadingMessage = document.querySelector('#loading');
// Show loading state
loadingMessage.classList.remove('hidden');
container.innerHTML = '';
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('Fetch failed');
const data = await response.json();
displayData(data, container);
} catch (error) {
container.innerHTML = '<p class="error">Unable to load content.</p>';
} finally {
// Always hide loading, whether success or failure
loadingMessage.classList.add('hidden');
}
}The finally block runs regardless of success or failure—perfect for cleanup like hiding loading spinners.
HTTP Methods: Beyond GET
So far we’ve used GET (fetching data). Other methods exist:
// POST - create new data
const response = await fetch('https://api.example.com/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
product: 'Coffee',
quantity: 2
})
});
// PUT - replace existing data
await fetch('https://api.example.com/orders/123', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ product: 'Tea', quantity: 3 })
});
// DELETE - remove data
await fetch('https://api.example.com/orders/123', {
method: 'DELETE'
});| Method | Purpose | Has Body? |
|---|---|---|
| GET | Read data | No |
| POST | Create new data | Yes |
| PUT | Replace data completely | Yes |
| PATCH | Update part of data | Yes |
| DELETE | Remove data | Usually no |
CORS: Why Some Requests Fail
You might encounter this error:
Access to fetch at ‘https://other-site.com/api’ has been blocked by CORS policy
CORS (Cross-Origin Resource Sharing) is a security feature. By default, JavaScript can only fetch from the same domain the page is on. To fetch from a different domain, that domain must explicitly allow it.
Ask your AI:
Explain CORS in simple terms. Why does it exist? What's it protecting
against?
As a frontend developer, you can’t fix CORS on a third-party server. Your options:
- Use APIs that allow CORS (most public APIs do)
- Ask the API provider to enable CORS
- Use a backend proxy (your server fetches the data)
Many APIs welcome frontend requests: JSONPlaceholder, OpenWeatherMap, GitHub API, and more. These are great for learning.
5.5 Building Your Mental Model
Request-Response Cycle
Every API interaction follows this pattern:
┌──────────────┐ Request ┌──────────────┐
│ │ ──────────────▶ │ │
│ Browser │ │ Server │
│ (Your JS) │ ◀────────────── │ (API) │
│ │ Response │ │
└──────────────┘ └──────────────┘
- Your JavaScript builds a request (URL, method, body, headers)
- Browser sends it across the network
- Server processes and responds
- Your JavaScript handles the response
Everything that can go wrong—network issues, server errors, malformed data—happens in this cycle.
Synchronous vs Asynchronous
Synchronous (blocking):
Step 1 → Wait → Step 2 → Wait → Step 3
Asynchronous (non-blocking):
Step 1 → Start Step 2 (don't wait) → Step 3
↓
Step 2 completes → Handle result
async/await makes asynchronous code look synchronous while keeping the page responsive.
The Data Flow
API Response (JSON string)
↓
response.json() (parse)
↓
JavaScript Objects/Arrays
↓
Process & Transform
↓
Create DOM Elements
↓
Page Updates
Understanding this flow helps debug issues: Is the problem in fetching? Parsing? Processing? Rendering?
5.6 Business Applications
Real-Time Data
Stock prices, sports scores, weather—APIs provide live data that keeps users engaged and informed. Without APIs, you’d need to manually update your site constantly.
Payment Processing
No one stores credit cards themselves (the liability is enormous). Payment APIs like Stripe, PayPal, and Square handle the sensitive parts, letting you focus on the shopping experience.
Third-Party Services
Maps (Google Maps, Mapbox), analytics (Google Analytics), authentication (Auth0), email (SendGrid)—APIs let you leverage sophisticated services without building them yourself.
Scalability and Architecture
Separating your frontend (the user interface) from your backend (the data and business logic) via APIs allows each to scale independently. Your static site can be served from a CDN worldwide while your API runs on dedicated servers.
Business Integration
Connect your website to: - Inventory management systems - Customer relationship management (CRM) - Email marketing platforms - Accounting software
APIs are how modern businesses connect their systems.
This develops ULO 4 (select and integrate technologies) and ULO 1 (design effective applications). API integration is fundamental to modern web development. Understanding how to evaluate, implement, and handle errors in API connections is essential professional knowledge.
5.7 Practice Exercises
- Level 1: Direct application
- Level 2: Minor modifications
- Level 3: Combining concepts
- Level 4: Problem-solving
- Level 5: Open-ended design
Exercise 4.1: Your First API Call (Level 1)
Use the JSONPlaceholder API (https://jsonplaceholder.typicode.com/posts/1) to:
- Fetch a single post using
fetch()andasync/await - Log the response to the console
- Display the post’s title and body in HTML elements
Open DevTools Network tab to see the request and response.
Exercise 4.2: Displaying a List (Level 2)
Fetch multiple posts from https://jsonplaceholder.typicode.com/posts?_limit=5 and:
- Create an HTML card for each post showing title and body
- Add proper loading and error states
- Style the cards with CSS
Handle what happens if the fetch fails.
Exercise 4.3: Dynamic Filtering (Level 3)
Using the JSONPlaceholder posts API:
- Fetch all posts (or limit to 20)
- Create a search input field
- As the user types, filter the displayed posts to those whose title contains the search term
- Update the display without re-fetching
This combines API fetching with JavaScript event handling and DOM manipulation.
Exercise 4.4: Error Handling Scenarios (Level 4)
Create a page that fetches from an API and handles all these scenarios gracefully:
- Successful fetch → Display data
- Network error (try an invalid URL) → Show connection error message
- 404 error (fetch a non-existent resource) → Show “not found” message
- Loading state → Show spinner while waiting
Test each scenario and document how you handled them. Take screenshots showing each state.
Exercise 4.5: API Integration Proposal (Level 5)
A local gym wants to display class schedules from their booking system on their website. The booking system has an API.
Research and propose:
- What data would you need from the API?
- How would you display it? (Sketch the UI)
- What loading states and error handling are needed?
- How often should data refresh?
- What happens if the API is unavailable?
Write a 400-word proposal. Discuss your approach with your AI partner—what did you miss?
5.8 Chapter Summary
- APIs enable systems to communicate through defined contracts
fetch()withasync/awaitmakes readable asynchronous code- JSON is the standard data format for web APIs
- Always handle loading states and errors
- Check
response.ok—fetch doesn’t throw on HTTP errors - CORS protects users but can block legitimate requests
- APIs connect your site to the broader ecosystem of services
5.9 Reflection
Before moving to the Portfolio Project, ensure you can:
5.10 Your Learning Journal
Record your responses to these prompts:
API Discovery: Find three public APIs that could be useful for business websites. What data do they provide? What would you build with them?
Error Empathy: Think about times you’ve seen error messages on websites. Which were helpful? Which were frustrating? How would you do better?
AI Conversation Reflection: What API concept was most confusing? What question to your AI partner helped clarify it?
Business Integration: Think of a local business. What data might they want to display from external sources? What APIs might provide it?
5.11 Next Steps
You’ve now completed Part I: Web Foundations. You understand:
- Structure (HTML): What content exists
- Presentation (CSS): How content looks
- Behaviour (JavaScript): How content responds
- Connection (APIs): How content integrates with external services
In Chapter 6, you’ll combine these skills to build a complete portfolio website—your first substantial web project. This portfolio will demonstrate your capabilities to future employers or clients.
Then, in Part II, we shift focus from building pages to managing content at scale with content management systems.