RESTful API 実践応用
ユーザー管理 API 設計
完全なユーザー管理システム API を設計しましょう。これは最も一般的なアプリケーションシナリオです。
API エンドポイント設計
// 用户相关操作
GET /api/users # 获取用户列表
GET /api/users/{id} # 获取特定用户
POST /api/users # 创建新用户
PUT /api/users/{id} # 更新用户信息
DELETE /api/users/{id} # 删除用户
// 用户订单相关操作
GET /api/users/{id}/orders # 获取用户的订单列表
POST /api/users/{id}/orders # 为用户创建订单
GET /api/orders/{orderId} # 获取特定订单详情完全な CRUD 操作
1. ユーザー作成(Create)
// 请求
POST /api/users
Content-Type: application/json
{
"name": "王五",
"email": "wangwu@example.com",
"phone": "13800000000",
"address": {
"city": "上海",
"street": "南京路100号"
}
}
// 成功响应(状态码:201 Created)
{
"success": true,
"data": {
"id": 125,
"name": "王五",
"email": "wangwu@example.com",
"phone": "13800000000",
"address": {
"city": "上海",
"street": "南京路100号"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
},
"message": "用户创建成功"
}2. ユーザー取得(Read)
// 获取用户列表
GET /api/users?page=1&limit=5&sort=createdAt&order=desc
// 响应(状态码:200 OK)
{
"success": true,
"data": [
{
"id": 125,
"name": "王五",
"email": "wangwu@example.com",
"createdAt": "2024-01-15T10:00:00Z"
},
{
"id": 124,
"name": "李四",
"email": "lisi@example.com",
"createdAt": "2024-01-15T09:00:00Z"
}
],
"pagination": {
"currentPage": 1,
"totalPages": 3,
"totalItems": 15,
"itemsPerPage": 5
}
}
// 获取特定用户
GET /api/users/125
// 响应
{
"success": true,
"data": {
"id": 125,
"name": "王五",
"email": "wangwu@example.com",
"phone": "13800000000",
"address": {
"city": "上海",
"street": "南京路100号"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
}
}3. ユーザー更新(Update)
// 请求
PUT /api/users/125
Content-Type: application/json
{
"name": "王五",
"email": "wangwu.new@example.com",
"phone": "13900000000",
"address": {
"city": "深圳",
"street": "科技园路200号"
}
}
// 响应(状态码:200 OK)
{
"success": true,
"data": {
"id": 125,
"name": "王五",
"email": "wangwu.new@example.com",
"phone": "13900000000",
"address": {
"city": "深圳",
"street": "科技园路200号"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T11:30:00Z"
},
"message": "用户信息更新成功"
}4. ユーザー削除(Delete)
// 请求
DELETE /api/users/125
// 响应(状态码:200 OK)
{
"success": true,
"message": "用户删除成功"
}
// 如果用户不存在(状态码:404 Not Found)
{
"success": false,
"error": {
"code": "USER_NOT_FOUND",
"message": "用户不存在"
}
}エラー処理
データ検証エラー
// 请求(邮箱格式错误)
POST /api/users
{
"name": "",
"email": "invalid-email",
"phone": "123"
}
// 响应(状态码:400 Bad Request)
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "数据验证失败",
"details": [
{
"field": "name",
"message": "姓名不能为空"
},
{
"field": "email",
"message": "邮箱格式不正确"
},
{
"field": "phone",
"message": "手机号格式不正确"
}
]
}
}リソースが見つからないエラー
// 请求
GET /api/users/999
// 响应(状态码:404 Not Found)
{
"success": false,
"error": {
"code": "USER_NOT_FOUND",
"message": "用户不存在"
}
}JavaScript を使用して API を呼び出す
実例
// fetch API を使用して RESTful API を呼び出す
// 1. ユーザーリストを取得
async function getUsers() {
try {
const response = await fetch('/api/users');
const result = await response.json();
if (result.success) {
console.log('ユーザーリスト:', result.data);
} else {
console.error('取得失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 2. 新規ユーザーを作成
async function createUser(userData) {
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const result = await response.json();
if (result.success) {
console.log('ユーザー作成成功:', result.data);
} else {
console.error('作成失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 3. ユーザー情報を更新
async function updateUser(userId, userData) {
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const result = await response.json();
if (result.success) {
console.log('ユーザー更新成功:', result.data);
} else {
console.error('更新失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 4. ユーザーを削除
async function deleteUser(userId) {
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.success) {
console.log('ユーザー削除成功');
} else {
console.error('削除失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 1. ユーザーリストを取得
async function getUsers() {
try {
const response = await fetch('/api/users');
const result = await response.json();
if (result.success) {
console.log('ユーザーリスト:', result.data);
} else {
console.error('取得失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 2. 新規ユーザーを作成
async function createUser(userData) {
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const result = await response.json();
if (result.success) {
console.log('ユーザー作成成功:', result.data);
} else {
console.error('作成失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 3. ユーザー情報を更新
async function updateUser(userId, userData) {
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const result = await response.json();
if (result.success) {
console.log('ユーザー更新成功:', result.data);
} else {
console.error('更新失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}
// 4. ユーザーを削除
async function deleteUser(userId) {
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.success) {
console.log('ユーザー削除成功');
} else {
console.error('削除失敗:', result.error.message);
}
} catch (error) {
console.error('ネットワークエラー:', error);
}
}