By the end of this lesson, you will:
ℹ️ Info GET vs POST So far, we've used GET to read data. Now we'll use POST to send data and create new things - like posting a comment, creating an account, or submitting a form!
GET Request | POST Request |
---|---|
Like reading a book | Like sending a letter |
Only retrieves data | Sends data to server |
Data in URL | Data in body |
Can bookmark | Can't bookmark |
Safe to repeat | Changes things |
fetch('https://api.example.com/users', {
method: 'POST', // 1. Specify POST method
headers: { // 2. Set headers
'Content-Type': 'application/json'
},
body: JSON.stringify({ // 3. Send data
name: 'Alex',
email: 'alex@example.com'
})
});
async function createTodo(task) {
const todoData = {
title: task,
completed: false,
userId: 1
};
const response = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(todoData)
});
const result = await response.json();
console.log('Created todo:', result);
return result;
}
// Use it
createTodo('Learn POST requests');
<form id="userForm">
<input type="text" id="name" placeholder="Your name">
<input type="email" id="email" placeholder="Your email">
<button type="submit">Submit</button>
</form>
<div id="result"></div>
document.getElementById('userForm').addEventListener('submit', async (e) => {
e.preventDefault(); // Stop page refresh
// Get form values
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value
};
// Send to API
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
if (response.ok) {
const user = await response.json();
document.getElementById('result').innerHTML =
`<p>✅ User created with ID: ${user.id}</p>`;
} else {
throw new Error('Failed to create user');
}
} catch (error) {
document.getElementById('result').innerHTML =
`<p>❌ Error: ${error.message}</p>`;
}
});
async function addComment(postId, text) {
// 1. Send to API
const response = await fetch(`/api/posts/${postId}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
});
// 2. Get created comment
const comment = await response.json();
// 3. Add to page
const html = `
<div class="comment">
<p>${comment.text}</p>
<small>Posted just now</small>
</div>
`;
document.getElementById('comments').innerHTML += html;
}
async function createPrivateNote(content) {
const apiKey = 'your-api-key';
const response = await fetch('https://api.notes.com/notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
content: content,
private: true
})
});
return await response.json();
}
// Sending JSON
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
});
// Sending form data
const formData = new FormData();
formData.append('username', 'alex');
formData.append('age', '16');
fetch('/api/form', {
method: 'POST',
body: formData // No Content-Type needed!
});
// Sending plain text
fetch('/api/message', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: 'Hello, this is plain text!'
});
class ContactForm {
constructor(apiEndpoint) {
this.apiEndpoint = apiEndpoint;
this.form = document.getElementById('contact');
this.setupEventListeners();
}
setupEventListeners() {
this.form.addEventListener('submit', (e) => {
e.preventDefault();
this.handleSubmit();
});
}
async handleSubmit() {
// Get form data
const data = {
name: this.form.name.value,
email: this.form.email.value,
message: this.form.message.value
};
// Validate
if (!data.name || !data.email || !data.message) {
this.showMessage('Please fill all fields', 'error');
return;
}
// Show loading
this.showMessage('Sending...', 'loading');
try {
// Send to API
const response = await fetch(this.apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (response.ok) {
this.showMessage('Message sent successfully!', 'success');
this.form.reset();
} else {
throw new Error('Failed to send');
}
} catch (error) {
this.showMessage('Error sending message', 'error');
}
}
showMessage(text, type) {
const messageDiv = document.getElementById('message');
messageDiv.className = type;
messageDiv.textContent = text;
}
}
// Use it
new ContactForm('https://api.example.com/contact');
async function safePost(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
// Check different error types
if (response.status === 400) {
throw new Error('Bad request - check your data');
}
if (response.status === 401) {
throw new Error('Not authorized - check API key');
}
if (response.status === 500) {
throw new Error('Server error - try again later');
}
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('POST failed:', error);
// Show user-friendly message
alert('Something went wrong. Please try again.');
return null;
}
}
// This API accepts POST but doesn't really save
async function testPost() {
const testData = {
title: 'My Test Post',
body: 'This is a test',
userId: 1
};
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(testData)
});
const result = await response.json();
console.log('Test result:', result);
// Will show: { id: 101, title: "My Test Post", ... }
}
Create a function that posts a note to an API:
// Complete this function
async function createNote(title, content) {
// Your code here
}
Add POST functionality to this form:
<form id="signup">
<input id="username" placeholder="Username">
<input id="password" type="password" placeholder="Password">
<button>Sign Up</button>
</form>
You've learned to:
POST requests let you create and modify data - essential for interactive applications!
Great progress! You now know the four fundamentals:
Next, we'll combine everything to build a complete Weather Dashboard application!