编写API的JSON预期格式包括定义API请求和响应的JSON数据结构。下面是一个示例解决方案,包含代码示例:
{
"method": "GET",
"path": "/api/users",
"query": {
"page": 1,
"limit": 10
},
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer token"
},
"body": {
"name": "John Doe",
"email": "johndoe@example.com"
}
}
在上述示例中,method
字段表示HTTP请求方法,path
字段表示API的路径,query
字段表示查询参数,headers
字段表示请求头,body
字段表示请求体。
{
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"data": [
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "janesmith@example.com"
}
]
}
}
在上述示例中,status
字段表示HTTP响应状态码,headers
字段表示响应头,body
字段表示响应体,其中data
字段表示实际的响应数据。
const express = require('express');
const app = express();
app.get('/api/users', (req, res) => {
const page = req.query.page || 1;
const limit = req.query.limit || 10;
// 假设从数据库中获取用户数据
const users = [
{ id: 1, name: 'John Doe', email: 'johndoe@example.com' },
{ id: 2, name: 'Jane Smith', email: 'janesmith@example.com' }
];
res.status(200).json({
status: 200,
headers: { 'Content-Type': 'application/json' },
body: { data: users }
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上述示例中,app.get
定义了一个GET请求的API,当请求路径为/api/users
时,会返回一个包含用户数据的JSON响应。
以上示例演示了如何定义API请求和响应的JSON预期格式,并提供了一个使用Node.js和Express的代码示例。你可以根据实际情况进行修改和扩展。