📋 CRUD App = REST API
CRUD operations are fundamental. Step-by-step guide to build a CRUD application with REST API.
📝 Step 1-4: API Setup
// Step 1: API Service
const API_URL = 'https://jsonplaceholder.typicode.com/posts';
class ApiService {
static async getPosts() {
const response = await fetch(API_URL);
if (!response.ok) throw new Error('Failed to fetch posts');
return response.json();
}
static async createPost(post) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
});
if (!response.ok) throw new Error('Failed to create post');
return response.json();
}
static async updatePost(id, post) {
const response = await fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
});
if (!response.ok) throw new Error('Failed to update post');
return response.json();
}
static async deletePost(id) {
const response = await fetch(`${API_URL}/${id}`, {
method: 'DELETE'
});
if (!response.ok) throw new Error('Failed to delete post');
return response;
}
}
// Step 2: HTML Structure
<div id="app">
<h1>Posts Management</h1>
<form id="post-form">
<input type="text" id="title" placeholder="Title" required>
<textarea id="body" placeholder="Body" required></textarea>
<input type="hidden" id="post-id">
<button type="submit">Add Post</button>
</form>
<div id="posts-list"></div>
</div>
📝 Step 5-8: CRUD Operations
// Step 5: Render Posts
async function renderPosts() {
try {
const posts = await ApiService.getPosts();
const container = document.getElementById('posts-list');
container.innerHTML = posts.map(post => `
<div class="post-card" data-id="${post.id}">
<h3>${post.title}</h3>
<p>${post.body}</p>
<div class="actions">
<button onclick="editPost('${post.id}')">Edit</button>
<button onclick="deletePost('${post.id}')">Delete</button>
</div>
</div>
`).join('');
} catch (error) {
console.error('Error rendering posts:', error);
}
}
// Step 6: Create/Update Post
document.getElementById('post-form').addEventListener('submit', async (e) => {
e.preventDefault();
const title = document.getElementById('title').value;
const body = document.getElementById('body').value;
const id = document.getElementById('post-id').value;
try {
if (id) {
await ApiService.updatePost(id, { title, body });
} else {
await ApiService.createPost({ title, body, userId: 1 });
}
document.getElementById('post-form').reset();
document.getElementById('post-id').value = '';
document.querySelector('button[type="submit"]').textContent = 'Add Post';
await renderPosts();
} catch (error) {
console.error('Error saving post:', error);
}
});
// Step 7: Edit Post
function editPost(id) {
const post = document.querySelector(`.post-card[data-id="${id}"]`);
const title = post.querySelector('h3').textContent;
const body = post.querySelector('p').textContent;
document.getElementById('title').value = title;
document.getElementById('body').value = body;
document.getElementById('post-id').value = id;
document.querySelector('button[type="submit"]').textContent = 'Update Post';
}
// Step 8: Delete Post
async function deletePost(id) {
if (!confirm('Are you sure you want to delete this post?')) return;
try {
await ApiService.deletePost(id);
await renderPosts();
} catch (error) {
console.error('Error deleting post:', error);
}
}
✅ CRUD App Features
- ✓ Create posts
- ✓ Read posts
- ✓ Update posts
- ✓ Delete posts
- ✓ Error handling
Building a CRUD application with REST API is the perfect way to master AJAX. It covers all the essential operations you’ll need.
