入门15分钟
JSONPlaceholder 完全指南
学习如何使用 JSONPlaceholder 测试API开发,掌握RESTful API的CRUD操作。
测试REST APIJSON开发工具
前提条件
- •了解 REST API 基本概念
- •JavaScript fetch 基础
什么是 JSONPlaceholder?
JSONPlaceholder 是一个免费的在线 REST API,专门用于测试和原型开发。它提供模拟的博客数据,包括文章、用户、评论等,你可以在上面练习所有 CRUD(增删改查)操作。
特点: - 完全免费,无需注册 - 支持 GET、POST、PUT、DELETE 等所有 HTTP 方法 - 返回标准的 JSON 数据 - 所有更改都是模拟的,不会真正保存
📖完整教程
1
第一步:获取文章列表 (GET)
使用 GET 请求获取所有文章。
javascript
// 获取所有文章
async function getPosts() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
console.log('文章数量:', posts.length);
console.log('第一篇文章:', posts[0]);
}
getPosts();
// 获取单个文章
async function getPost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
const post = await response.json();
return post;
}
getPost(1); // 获取ID为1的文章
// 按用户筛选文章
async function getPostsByUser(userId) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);
return await response.json();
}
getPostsByUser(1); // 获取用户1的所有文章💡 提示
- •GET 请求不会修改数据,可以放心测试
- •使用 ?userId=1 这样的查询参数进行筛选
- •URL 最后的 /1 表示获取 ID 为 1 的资源
2
第二步:创建新文章 (POST)
使用 POST 请求创建新文章。
javascript
// 创建新文章
async function createPost(title, body, userId) {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: title,
body: body,
userId: userId
})
});
const newPost = await response.json();
console.log('创建的文章:', newPost);
// 返回: { id: 101, title: '...', body: '...', userId: 1 }
// 注意:ID 是模拟的,实际不会保存
return newPost;
}
createPost(
'我的第一篇文章',
'这是文章的内容...',
1
);💡 提示
- •POST 用于创建新资源
- •请求体使用 JSON 格式
- •Content-Type 必须设置为 application/json
- •服务器会返回新创建的资源,包含模拟的 ID
3
第三步:更新文章 (PUT/PATCH)
使用 PUT 或 PATCH 请求更新文章。
javascript
// PUT:完全替换文章
async function updatePost(id, title, body, userId) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: id,
title: title,
body: body,
userId: userId
})
});
return await response.json();
}
// PATCH:部分更新文章
async function patchPost(id, updates) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updates)
});
return await response.json();
}
// 示例:只更新标题
patchPost(1, { title: '新标题' });💡 提示
- •PUT 替换整个资源,需要提供所有字段
- •PATCH 只更新指定的字段,更灵活
- •两个方法都需要提供完整的 URL(包括 ID)
4
第四步:删除文章 (DELETE)
使用 DELETE 请求删除文章。
javascript
// 删除文章
async function deletePost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'DELETE'
});
if (response.ok) {
console.log(`文章 ${id} 已删除`);
return true;
}
return false;
}
deletePost(1);
// 完整示例:博客应用 CRUD
class BlogAPI {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async getAllPosts() {
return fetch(`${this.baseUrl}/posts`).then(r => r.json());
}
async getPost(id) {
return fetch(`${this.baseUrl}/posts/${id}`).then(r => r.json());
}
async createPost(data) {
return fetch(`${this.baseUrl}/posts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}).then(r => r.json());
}
async updatePost(id, data) {
return fetch(`${this.baseUrl}/posts/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}).then(r => r.json());
}
async deletePost(id) {
return fetch(`${this.baseUrl}/posts/${id}`, {
method: 'DELETE'
}).then(r => r.ok);
}
}
const api = new BlogAPI('https://jsonplaceholder.typicode.com');💡 提示
- •DELETE 请求没有请求体
- •成功返回空对象 {} 或空响应
- •JSONPlaceholder 的删除是模拟的,数据不会真正消失