Skip to content

17.4 接口开发(返回 JSON)

什么是 API

API(Application Programming Interface,应用程序编程接口)是不同软件组件之间的通信协议,它定义了如何与应用程序交互。在 Web 开发中,API 通常是指 HTTP API,通过 HTTP 请求和响应来交换数据。

JSON 格式

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它易于阅读和编写,也易于机器解析和生成。JSON 格式的数据结构包括:

  • 对象:用 {} 表示,包含键值对
  • 数组:用 [] 表示,包含有序的值
  • :可以是字符串、数字、布尔值、null、对象或数组

PHP 实现 JSON API

1. 基本 JSON 响应

php
<?php
// 设置响应头
header('Content-Type: application/json');

// 准备数据
$data = [
    'status' => 'success',
    'message' => '操作成功',
    'data' => [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]
];

// 输出 JSON
echo json_encode($data);
?>

2. 处理 GET 请求

php
<?php
// 设置响应头
header('Content-Type: application/json');

// 获取查询参数
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// 模拟数据
$users = [
    1 => [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ],
    2 => [
        'id' => 2,
        'name' => 'Jane Smith',
        'email' => 'jane@example.com'
    ]
];

// 处理请求
if ($id > 0) {
    if (isset($users[$id])) {
        $response = [
            'status' => 'success',
            'data' => $users[$id]
        ];
    } else {
        $response = [
            'status' => 'error',
            'message' => '用户不存在'
        ];
    }
} else {
    $response = [
        'status' => 'success',
        'data' => $users
    ];
}

// 输出 JSON
echo json_encode($response);
?>

3. 处理 POST 请求

php
<?php
// 设置响应头
header('Content-Type: application/json');

// 获取 POST 数据
$input = json_decode(file_get_contents('php://input'), true);

// 验证数据
if (!isset($input['name']) || !isset($input['email'])) {
    $response = [
        'status' => 'error',
        'message' => '缺少必要参数'
    ];
} else {
    // 模拟保存数据
    $user = [
        'id' => uniqid(),
        'name' => $input['name'],
        'email' => $input['email'],
        'created_at' => date('Y-m-d H:i:s')
    ];
    
    $response = [
        'status' => 'success',
        'message' => '用户创建成功',
        'data' => $user
    ];
}

// 输出 JSON
echo json_encode($response);
?>

4. 处理 PUT 请求

php
<?php
// 设置响应头
header('Content-Type: application/json');

// 获取 PUT 数据
parse_str(file_get_contents('php://input'), $input);

// 获取用户 ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// 验证数据
if ($id <= 0 || !isset($input['name']) || !isset($input['email'])) {
    $response = [
        'status' => 'error',
        'message' => '缺少必要参数'
    ];
} else {
    // 模拟更新数据
    $user = [
        'id' => $id,
        'name' => $input['name'],
        'email' => $input['email'],
        'updated_at' => date('Y-m-d H:i:s')
    ];
    
    $response = [
        'status' => 'success',
        'message' => '用户更新成功',
        'data' => $user
    ];
}

// 输出 JSON
echo json_encode($response);
?>

5. 处理 DELETE 请求

php
<?php
// 设置响应头
header('Content-Type: application/json');

// 获取用户 ID
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// 验证数据
if ($id <= 0) {
    $response = [
        'status' => 'error',
        'message' => '缺少必要参数'
    ];
} else {
    // 模拟删除数据
    $response = [
        'status' => 'success',
        'message' => '用户删除成功'
    ];
}

// 输出 JSON
echo json_encode($response);
?>

API 设计最佳实践

  1. 使用 RESTful 设计:遵循 REST 原则,使用合适的 HTTP 方法
  2. 使用标准状态码:使用 HTTP 状态码表示请求结果
  3. 提供一致的响应格式:统一响应格式,包括状态、消息和数据
  4. 实现错误处理:对错误进行适当的处理和返回
  5. 使用 HTTPS:确保 API 通信安全
  6. 实现认证:对敏感操作进行身份验证
  7. 提供 API 文档:详细说明 API 的使用方法
  8. 实现速率限制:防止 API 被滥用

实战演练

场景:用户管理 API

php
<?php
// api.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

// 模拟数据库
$users = [
    1 => [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'created_at' => '2023-01-01 10:00:00'
    ],
    2 => [
        'id' => 2,
        'name' => 'Jane Smith',
        'email' => 'jane@example.com',
        'created_at' => '2023-01-02 11:00:00'
    ]
];

// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];

// 处理不同的请求方法
switch ($method) {
    case 'GET':
        // 处理 GET 请求
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($id > 0) {
            if (isset($users[$id])) {
                $response = [
                    'status' => 'success',
                    'data' => $users[$id]
                ];
            } else {
                $response = [
                    'status' => 'error',
                    'message' => '用户不存在'
                ];
            }
        } else {
            $response = [
                'status' => 'success',
                'data' => array_values($users)
            ];
        }
        break;
        
    case 'POST':
        // 处理 POST 请求
        $input = json_decode(file_get_contents('php://input'), true);
        if (!isset($input['name']) || !isset($input['email'])) {
            $response = [
                'status' => 'error',
                'message' => '缺少必要参数'
            ];
        } else {
            $id = count($users) + 1;
            $users[$id] = [
                'id' => $id,
                'name' => $input['name'],
                'email' => $input['email'],
                'created_at' => date('Y-m-d H:i:s')
            ];
            $response = [
                'status' => 'success',
                'message' => '用户创建成功',
                'data' => $users[$id]
            ];
        }
        break;
        
    case 'PUT':
        // 处理 PUT 请求
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        $input = json_decode(file_get_contents('php://input'), true);
        if ($id <= 0 || !isset($input['name']) || !isset($input['email'])) {
            $response = [
                'status' => 'error',
                'message' => '缺少必要参数'
            ];
        } else if (!isset($users[$id])) {
            $response = [
                'status' => 'error',
                'message' => '用户不存在'
            ];
        } else {
            $users[$id]['name'] = $input['name'];
            $users[$id]['email'] = $input['email'];
            $users[$id]['updated_at'] = date('Y-m-d H:i:s');
            $response = [
                'status' => 'success',
                'message' => '用户更新成功',
                'data' => $users[$id]
            ];
        }
        break;
        
    case 'DELETE':
        // 处理 DELETE 请求
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if ($id <= 0) {
            $response = [
                'status' => 'error',
                'message' => '缺少必要参数'
            ];
        } else if (!isset($users[$id])) {
            $response = [
                'status' => 'error',
                'message' => '用户不存在'
            ];
        } else {
            unset($users[$id]);
            $response = [
                'status' => 'success',
                'message' => '用户删除成功'
            ];
        }
        break;
        
    default:
        $response = [
            'status' => 'error',
            'message' => '不支持的请求方法'
        ];
        break;
}

// 输出 JSON
echo json_encode($response);
?>

场景:使用 curl 测试 API

bash
# 获取所有用户
curl http://localhost/api.php

# 获取单个用户
curl http://localhost/api.php?id=1

# 创建用户
curl -X POST -H "Content-Type: application/json" -d '{"name":"Bob Brown","email":"bob@example.com"}' http://localhost/api.php

# 更新用户
curl -X PUT -H "Content-Type: application/json" -d '{"name":"Bob Smith","email":"bob.smith@example.com"}' http://localhost/api.php?id=3

# 删除用户
curl -X DELETE http://localhost/api.php?id=3

场景:使用 JavaScript 调用 API

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API 测试</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <h1>用户管理 API 测试</h1>
    
    <div id="result"></div>
    
    <script>
        // 获取所有用户
        async function getUsers() {
            try {
                const response = await axios.get('http://localhost/api.php');
                document.getElementById('result').innerHTML = JSON.stringify(response.data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }
        
        // 获取单个用户
        async function getUser(id) {
            try {
                const response = await axios.get(`http://localhost/api.php?id=${id}`);
                document.getElementById('result').innerHTML = JSON.stringify(response.data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }
        
        // 创建用户
        async function createUser() {
            try {
                const response = await axios.post('http://localhost/api.php', {
                    name: 'Bob Brown',
                    email: 'bob@example.com'
                });
                document.getElementById('result').innerHTML = JSON.stringify(response.data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }
        
        // 调用函数
        getUsers();
    </script>
</body>
</html>

总结

API 开发是 Web 应用程序中的重要组成部分,它允许不同的应用程序之间进行数据交换。PHP 提供了简单的方法来实现 JSON API,通过设置适当的响应头和使用 json_encode 函数将数据转换为 JSON 格式。

在开发 API 时,应该遵循 RESTful 设计原则,使用标准的 HTTP 方法和状态码,提供一致的响应格式,实现适当的错误处理,确保 API 通信安全,并提供详细的 API 文档。

通过合理实现 API,可以构建更加灵活、可扩展的 Web 应用程序,支持多种客户端(如网页、移动应用、桌面应用等)的访问。

© 2026 编程马·菜鸟教程 版权所有