Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

RESTful API Request and Response Format

RESTful API Request and Response Format

JSON Format

Modern RESTful APIs primarily use JSON (JavaScript Object Notation) to transmit data.

JSON is like a universal language for data, simple and easy to read.

JSON Basic Syntax

{

  "name": "张三",

  "age": 25,

  "email": "zhangsan@example.com",

  "hobbies": ["阅读", "游泳", "编程"],

  "address": {

    "city": "北京",

    "district": "朝阳区"

  },

  "isActive": true

}

Request Format

GET Request Example:

// 请求

GET /api/users/123

Accept: application/json



// 响应

{

  "id": 123,

  "name": "张三",

  "email": "zhangsan@example.com",

  "createdAt": "2024-01-15T08:30:00Z"

}

POST Request Example:

// 请求

POST /api/users

Content-Type: application/json



{

  "name": "李四",

  "email": "lisi@example.com",

  "password": "securePassword123"

}



// 响应

{

  "id": 124,

  "name": "李四",

  "email": "lisi@example.com",

  "createdAt": "2024-01-15T09:00:00Z",

  "message": "用户创建成功"

}


Response Structure Design

Unified Response Format

{

  "success": true,

  "data": {

    "id": 123,

    "name": "张三"

  },

  "message": "操作成功",

  "timestamp": "2024-01-15T08:30:00Z"

}

Error Response Format

{

  "success": false,

  "error": {

    "code": "VALIDATION_ERROR",

    "message": "输入数据验证失败",

    "details": [

      {

        "field": "email",

        "message": "邮箱格式不正确"

      }

    ]

  },

  "timestamp": "2024-01-15T08:30:00Z"

}

Paginated Response

{

  "success": true,

  "data": [

    {

      "id": 1,

      "name": "用户1"

    },

    {

      "id": 2,

      "name": "用户2"

    }

  ],

  "pagination": {

    "currentPage": 1,

    "totalPages": 10,

    "totalItems": 100,

    "itemsPerPage": 10

  }

}

Common Request Header Fields

Field Name Purpose Example
Content-Type Request Body Data Format application/json
Accept Expected Response Format application/json
Authorization Authentication Information Bearer token123
User-Agent Client Information MyApp/1.0