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

RESTful API in Practice

RESTful API in Practice

User management API design

Let's design a complete user management system API, which is the most common use case.

API endpoint design

// 用户相关操作

GET    /api/users           # 获取用户列表

GET    /api/users/{id}      # 获取特定用户

POST   /api/users           # 创建新用户

PUT    /api/users/{id}      # 更新用户信息

DELETE /api/users/{id}      # 删除用户



// User order related operations

GET    /api/users/{id}/orders     # 获取用户的订单列表

POST   /api/users/{id}/orders     # 为用户创建订单

GET    /api/orders/{orderId}      # 获取特定订单详情


Complete CRUD operations

1. Create user (Create)

// 请求

POST /api/users

Content-Type: application/json



{

  "name": "王五",

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

  "phone": "13800000000",

  "address": {

    "city": "上海",

    "street": "南京路100号"

  }

}



// Success response (status code: 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 user (Read)

// 获取用户列表

GET /api/users?page=1&limit=5&sort=createdAt&order=desc



// Response (Status Code: 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 specific user

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 user (Update)

// 请求

PUT /api/users/125

Content-Type: application/json



{

  "name": "王五",

  "email": "wangwu.new@example.com",

  "phone": "13900000000",

  "address": {

    "city": "深圳",

    "street": "科技园路200号"

  }

}



// Response (Status Code: 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 user (Delete)

// 请求

DELETE /api/users/125



// Response (Status Code: 200 OK)

{

  "success": true,

  "message": "用户删除成功"

}



// If the user does not exist (status code: 404 Not Found)

{

  "success": false,

  "error": {

    "code": "USER_NOT_FOUND", 

    "message": "用户不存在"

  }

}


Error handling

Data validation error

// 请求(邮箱格式错误)

POST /api/users

{

  "name": "",

  "email": "invalid-email",

  "phone": "123"

}



// Response (Status Code: 400 Bad Request)

{

  "success": false,

  "error": {

    "code": "VALIDATION_ERROR",

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

    "details": [

      {

        "field": "name",

        "message": "姓名不能为空"

      },

      {

        "field": "email", 

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

      },

      {

        "field": "phone",

        "message": "手机号格式不正确"

      }

    ]

  }

}

Resource not found error

// 请求

GET /api/users/999



// Response (Status Code: 404 Not Found)

{

  "success": false,

  "error": {

    "code": "USER_NOT_FOUND",

    "message": "用户不存在"

  }

}


Calling the API with JavaScript

Example

// Use the fetch API to call the RESTful API

// 1. Get the user list

async

function

getUsers

(

)

{

 

try

{

   

const

response

=

await fetch

(

'/api/users'

)

;

   

const

result

=

await response.

json

(

)

;

   

   

if

(

result.

success

)

{

      console.

log

(

'User list:'

,

result.

data

)

;

   

}

else

{

      console.

error

(

'Fetch failed:'

,

result.

error

.

message

)

;

   

}

 

}

catch

(

error

)

{

    console.

error

(

'Network error:'

,

error

)

;

 

}

}

// 2. Create a new user

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

(

'User created successfully:'

,

result.

data

)

;

   

}

else

{

      console.

error

(

'Creation failed:'

,

result.

error

.

message

)

;

   

}

 

}

catch

(

error

)

{

    console.

error

(

'Network error:'

,

error

)

;

 

}

}

// 3. Update user information

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

(

'User updated successfully:'

,

result.

data

)

;

   

}

else

{

      console.

error

(

'Update failed:'

,

result.

error

.

message

)

;

   

}

 

}

catch

(

error

)

{

    console.

error

(

'Network error:'

,

error

)

;

 

}

}

// 4. Delete user

async

function

deleteUser

(

userId

)

{

 

try

{

   

const

response

=

await fetch

(

`

/

api

/

users

/

$

{

userId

}

`

,

{

      method

:

'DELETE'

   

}

)

;

   

   

const

result

=

await response.

json

(

)

;

   

   

if

(

result.

success

)

{

      console.

log

(

'User deleted successfully'

)

;

   

}

else

{

      console.

error

(

'Deletion failed:'

,

result.

error

.

message

)

;

   

}

 

}

catch

(

error

)

{

    console.

error

(

'Network error:'

,

error

)

;

 

}

}