HCDD 411
1 / 23

API

Md Touhidul Islam

Interactive slides + runnable examples (AJAX, Axios, Fetch)

Typical Web Application Structure

πŸ–₯️ Frontend (Client-side)

  • HTML
  • CSS
  • JavaScript
  • Frameworks: React / Angular / Vue

🧠 Backend (Server-side)

  • Processes requests
  • Performs business logic
  • Interacts with database (if needed)

πŸ—„οΈ Database

  • Store data
  • Retrieve data
  • Update data
  • Delete data

Frontend ↔ Backend Communication

Why APIs are common:
  • Ease of Use
  • Scalability
  • Separation of concerns
  • Standardized Communication
  • Security

API Key Components

PLAYGROUND: Endpoint + Method (Mental Model)
πŸ“„ endpoint.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

XML vs JSON (Data Formats)

🧩 XML (Extensible Markup Language)

  • Structured format for storing/exchanging data
  • Uses tags
  • Supports string only (in this lecture context)
  • Slower to parse

⚑ JSON (JavaScript Object Notation)

  • Structured format for storing/exchanging data
  • Key-value pairs
  • Key must be string (double quotes)
  • Value supports: string, number, boolean, array, object, null
  • Faster and lightweight

JSON Object vs JSON String

PLAYGROUND: JSON.parse() & JSON.stringify()
πŸ“„ json.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Data Exchange Techniques

Basic requirements (all three):
  • All can make HTTP requests
  • All work asynchronously
  • All can handle JSON data

πŸ•°οΈ AJAX

Classic approach (often taught with jQuery): asynchronous requests, update parts of page.

πŸ“¦ AXIOS

Promise-based client with simpler syntax + automatic JSON parsing.

πŸš€ FETCH API

Built-in browser API; modern, lightweight, very common.

πŸ’‘ Note: These playground examples call https://jsonplaceholder.typicode.com. You need an internet connection to see real responses.

AJAX (Asynchronous JavaScript and XML)

MINI DEMO: Async mental model
πŸ“„ async.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

jQuery AJAX

Syntax: $.ajax({})

⚠️ Common gotcha: For JSON requests, you often need JSON.stringify(...) for the request body (especially with jQuery / Fetch).

jQuery AJAX – GET

RUN: jQuery AJAX GET
πŸ“„ jquery-get.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

jQuery AJAX – POST

RUN: jQuery AJAX POST
πŸ“„ jquery-post.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

jQuery AJAX – PUT

RUN: jQuery AJAX PUT
πŸ“„ jquery-put.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Practice #1 β€” jQuery AJAX (GET + Render)

Goal:
  • Make a GET request to /users
  • Log how many users you received
  • Render each user name into the list below

βœ… Output target (DOM)

PRACTICE: Fill the TODOs and Run
πŸ“„ practice-1.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:
Hint: Use users.forEach(function(u){ ... }) and append like: $("#pp1-users").append("<li>" + u.name + "</li>")

Practice #2 β€” jQuery AJAX (POST + JSON)

Common gotcha: For JSON POST in jQuery, you usually need:
  • contentType: "application/json"
  • data: JSON.stringify({...})
Goal:
  • Send a POST request to /posts
  • Log the returned id from the created post
  • Handle errors (log xhr.status)
PRACTICE: Fill the TODOs and Run
πŸ“„ practice-2.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:
Suggested payload: { title: "Practice Post", body: "Hello from HCDD 411", userId: 1 }

jQuery AJAX – DELETE

RUN: jQuery AJAX DELETE
πŸ“„ jquery-delete.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Promises: Why .then() and .catch()?

Key idea: Promises avoid β€œcallback nesting” and make async code easier to compose.
  • .then(...) = β€œwhen it succeeds, do this”
  • .catch(...) = β€œif it fails, do this”
RUN: Promise + then/catch order
πŸ“„ promise.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Axios: Setup + Run (Step-by-step)

🌐 In the Browser

  • Add Axios via CDN (a script tag)
  • Then axios.get(...) works immediately
  • Great for small demos / learning

🧰 In Node.js

  • Install: npm i axios
  • Import: const axios = require("axios")
  • Run: node app.js

βœ… Why students like Axios

  • Auto JSON parsing (response is already usable)
  • Response payload is in response.data
  • Cleaner POST syntax vs jQuery AJAX
Step-by-step (browser):
  1. Include Axios (CDN) before your script
  2. Call axios.get(url) β†’ returns a Promise
  3. Use .then(...) (or await)
  4. Read the JSON from response.data
RUN: Verify Axios is loaded + make a request
πŸ“„ axios-setup.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

jQuery AJAX vs Axios: What changes?

Big picture:
  • jQuery AJAX: you pass options + callbacks (success/error)
  • Axios: you call a method (get/post/put/delete) and handle a Promise (.then/.catch)

Request body

  • jQuery: usually needs JSON.stringify(data)
  • Axios: just pass a JS object

Response

  • jQuery: response is already an object
  • Axios: response payload is in response.data

Errors

  • jQuery: error: function(err){...}
  • Axios: .catch(err => ...)
RUN: Same GET request (jQuery vs Axios)
πŸ“„ compare.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Fetch: Step-by-step (What happens?)

Common confusion: Fetch does NOT auto-parse JSON, and does not automatically throw on HTTP 404/500.
  • You should check response.ok and throw an error yourself
RUN: Fetch with status + ok + JSON parsing
πŸ“„ fetch-steps.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

async / await: How to use it (Step-by-step)

Translation in your head:
  • await something() β‰ˆ something().then(...) (same idea, easier to read)
  • But await only works inside an async function (in this lecture style)
RUN: await inside async + try/catch
πŸ“„ await.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:
If you get an β€œawait is only valid…” error: it means you used await outside an async function (or outside an ES module).

AXIOS

Core idea: Axios is a promise-based HTTP client:
  • Use .then() to handle success
  • Use .catch() to handle errors

AXIOS – Code Example

RUN: Axios GET + POST
πŸ“„ axios.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

FETCH API

Important: Fetch requires manual JSON parsing:
  • .then((response) => response.json())
  • or const data = await response.json()

FETCH API – Code Example

RUN: Fetch GET + POST
πŸ“„ fetch.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Modern Approach – async/await

RUN: async/await (Fetch + Axios)
πŸ“„ async-await.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:
JSON handling comparison:
  • jQuery AJAX: manually stringify request body; auto-parse JSON response into JS object.
  • AXIOS: auto stringify request body; auto-parse JSON response.
  • FETCH API: manually stringify request body; manually parse JSON response.

Practice #3 β€” Fetch (async/await + Error Handling)

Goal:
  • Write async function getUserEmail(id)
  • Use fetch, check response.ok, then await response.json()
  • Return the user’s email
PRACTICE: Complete the function and Run
πŸ“„ practice-3.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:

Practice #4 β€” Axios (Filter + Map)

Goal:
  • Use Axios to fetch /posts
  • Filter posts where userId === 1
  • Log only the first 5 titles
PRACTICE: Use axios.get + response.data
πŸ“„ practice-4.js
Ln 1, Col 1
JavaScript
Tab Indent Ctrl+Enter Run Ctrl+/ Comment
πŸ’» Console Output:
Hint: Use: posts.filter(...).slice(0, 5).forEach(...)