Skip to main content

Fetch API Basics

Level: Beginner

ℹ️ What You'll Learn
  • What Fetch API Basics means in JavaScript
  • Why this topic matters in real web pages
  • How to use it with School Management System examples
  • Common beginner mistakes to avoid
  • How to explain this topic in interviews

Why This Matters

Fetch API Basics is part of the practical frontend foundation. You will use it when building forms, tables, dashboards, reports, and API-connected screens for ASP.NET Core or full-stack projects.

Make HTTP requests to your backend API using Fetch.

The Problem

Beginners often copy JavaScript code without understanding what each line does. In a real School Management System, that leads to pages that are hard to maintain, hard to debug, or confusing for users. This lesson focuses on understanding the pattern first, then applying it in small practical examples.

Basic GET Request

// Simple GET request
async function getStudents() {
try {
const response = await fetch('/api/students');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}

getStudents();

Steps:

  1. fetch(url) — Start request
  2. await response — Wait for response
  3. response.json() — Parse JSON body
  4. Use data

Basic POST Request

// POST request with data
async function registerStudent(studentData) {
try {
const response = await fetch('/api/students', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(studentData)
});

const result = await response.json();
console.log('Created student:', result);
} catch (error) {
console.error('Error:', error);
}
}

// Use it
const student = {
name: 'Ravi Kumar',
email: 'ravi@example.com',
className: '10'
};

registerStudent(student);

Fetch Options

fetch('/api/endpoint', {
method: 'GET', // HTTP method
headers: { // Request headers
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify(data), // Request body (POST/PUT)
credentials: 'include' // Include cookies
});

Response Object

const response = await fetch('/api/students');

// Properties
console.log(response.status); // 200, 404, 500
console.log(response.ok); // true if 200-299
console.log(response.headers); // Response headers
console.log(response.statusText); // "OK", "Not Found"

// Methods
const json = await response.json();
const text = await response.text();
const blob = await response.blob();

Check Response Status

async function safeRequest(url) {
try {
const response = await fetch(url);

// Check if successful
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

const data = await response.json();
return data;
} catch (error) {
console.error('Request failed:', error);
}
}

All HTTP Methods

// GET - Read data
fetch('/api/students', { method: 'GET' });

// POST - Create data
fetch('/api/students', {
method: 'POST',
body: JSON.stringify({ name: 'Ravi' })
});

// PUT - Update entire object
fetch('/api/students/101', {
method: 'PUT',
body: JSON.stringify({ name: 'Ravi Kumar', className: '10' })
});

// PATCH - Update specific fields
fetch('/api/students/101', {
method: 'PATCH',
body: JSON.stringify({ className: '11' })
});

// DELETE - Delete resource
fetch('/api/students/101', { method: 'DELETE' });

Real SMS Example

// Get all students
async function loadStudents() {
try {
const response = await fetch('/api/students');
const students = await response.json();
console.log('Students:', students);
// Display in table (next topic)
} catch (error) {
console.error('Failed to load students:', error);
}
}

// Register new student
async function submitStudentForm(formData) {
try {
const response = await fetch('/api/students/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});

if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}

const student = await response.json();
console.log('Student registered:', student);
alert('Student registered successfully!');
} catch (error) {
console.error('Registration failed:', error);
alert('Error: ' + error.message);
}
}

// Get single student
async function getStudent(studentId) {
try {
const response = await fetch(`/api/students/${studentId}`);
const student = await response.json();
console.log('Student:', student);
return student;
} catch (error) {
console.error('Failed to load student:', error);
}
}

// Update student
async function updateStudent(studentId, updates) {
try {
const response = await fetch(`/api/students/${studentId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates)
});

const student = await response.json();
console.log('Updated student:', student);
} catch (error) {
console.error('Update failed:', error);
}
}

// Delete student
async function deleteStudent(studentId) {
try {
const response = await fetch(`/api/students/${studentId}`, {
method: 'DELETE'
});

if (response.ok) {
console.log('Student deleted');
}
} catch (error) {
console.error('Delete failed:', error);
}
}

Common Headers

headers: {
'Content-Type': 'application/json', // Sending JSON
'Accept': 'application/json', // Expect JSON
'Authorization': 'Bearer YOUR_TOKEN', // Auth token
'X-Requested-With': 'XMLHttpRequest' // Custom header
}

Key Takeaways

  • fetch() makes HTTP requests
  • Always check response.ok
  • Parse response with .json()
  • Use try/catch for errors
  • Different methods for different operations
  • Next: POST/GET requests details
💡 Backend Developer Tip

Print all responses to console first. Check what your API actually returns before writing complex code.

⚠️ Fetch Mistakes
  1. Not checking response.ok — Parse error on 404
  2. Forgetting JSON.stringify() — Server gets null
  3. Calling fetch without await — Gets promise, not data
  4. Wrong Content-Type header — Server rejects request
  5. CORS errors — Enable CORS on backend
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Fetch API. Try these prompts:

  • "When use GET vs POST?"
  • "What does response.ok do?"
  • "How do you send JSON data?"
  • "Quiz me on Fetch API"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • Fetch API Basics - The main concept explained in this lesson.
  • Selector/element/data - The page item or value you work with while applying this concept.
  • Real project usage - How this appears in forms, tables, dashboards, or API-connected pages.

Common Mistakes

  • Copying code without understanding what each line does
  • Forgetting to test with real School Management System data
  • Ignoring mobile screens and accessibility
  • Mixing structure, styling, and behavior in a confusing way
  • Not checking browser DevTools when something does not work

Practice Task

Create a small School Management System example using Fetch API Basics. Keep it simple first, then improve it step by step.

Suggested practice:

  1. Build a small student-related screen or component.
  2. Use clear names for elements, classes, variables, or functions.
  3. Test one success case and one failure case.
  4. Explain the code in your own words.
  5. Rebuild it once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Understand and apply Fetch API Basics in a real page.
Where is it used?Student forms, reports, dashboards, and admin screens.
What should beginners focus on?Clear structure, small examples, and repeated practice.
What is the best debugging habit?Inspect the page in browser DevTools and test one change at a time.
🎯 How would you explain Fetch API Basics in an interview?

Fetch API Basics is a practical JavaScript concept used to build clear, maintainable web pages. I would explain what problem it solves, show a small example, and mention one common mistake beginners should avoid.

🎯 Where is this used in a real project?

It is used in screens like student registration, attendance entry, marks reports, dashboards, and API-connected admin pages.

Next Article

Variables and Data Types ->

nexcoding.in