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

RESTful API Testing and Debugging

RESTful API Testing and Debugging

Testing APIs with tools

1. Postman testing

Postman is the most popular API testing tool, like a "playground" for APIs.

Postman official website address:https://www.postman.com/.

Basic testing steps:

  1. Create a new request
  2. Set the HTTP method (GET, POST, etc.)
  3. Enter the API address
  4. Add request headers and request body
  5. Send the request and view the response

Postman collection example:

{

  "info": {

    "name": "用户管理 API 测试",

    "description": "测试用户相关的所有 API 端点"

  },

  "item": [

    {

      "name": "获取用户列表",

      "request": {

        "method": "GET",

        "header": [],

        "url": {

          "raw": "{{baseUrl}}/api/users?page=1&limit=10",

          "host": ["{{baseUrl}}"],

          "path": ["api", "users"],

          "query": [

            {"key": "page", "value": "1"},

            {"key": "limit", "value": "10"}

          ]

        }

      }

    }

  ]

}

2. curl command-line testing

# 获取用户列表

curl -X GET "https://api.example.com/users" \

     -H "Content-Type: application/json"



# Create new user

curl -X POST "https://api.example.com/users" \

     -H "Content-Type: application/json" \

     -d '{

       "name": "张三",

       "email": "zhangsan@example.com"

     }'



# Update user information

curl -X PUT "https://api.example.com/users/123" \

     -H "Content-Type: application/json" \

     -d '{

       "name": "李四",

       "email": "lisi@example.com"

     }'



# Delete user

curl -X DELETE "https://api.example.com/users/123" \

     -H "Content-Type: application/json"

3. Browser developer tools

// 在浏览器控制台中测试

fetch('/api/users', {

  method: 'GET',

  headers: {

    'Content-Type': 'application/json'

  }

})

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error('Error:', error));


Debugging common issues

1. CORS cross-origin issue

Error message:



Access to fetch at 'https://api.example.com/users' from origin 'http://localhost:3000' 

has been blocked by CORS policy

Solutions:

// 服务器端需要设置 CORS 头

app.use((req, res, next) => {

  res.header('Access-Control-Allow-Origin', '*');

  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

  next();

});

2. Status code errors

Common errors and causes:

Status code Possible cause Solution
400 Incorrect request data format Check the JSON format and required fields
401 Authentication failed Check whether the token is correct
404 Incorrect API path Make sure the URL is spelled correctly
500 Internal server error Check the server logs

3. Data format issues

// 错误的请求格式

{

  name: "张三",  // ❌ 缺少引号

  'email': "test@example.com",  // ❌ 单引号

  age: "25"  // ❌ 数字用了字符串

}



// Correct request format

{

  "name": "张三",  // ✅ 双引号

  "email": "test@example.com",  // ✅ 双引号

  "age": 25  // ✅ 数字类型

}


Automated testing

Unit test example

Example

// Use the Jest testing framework

describe

(

'User API test'

,

(

)

=>

{

  test

(

'should be able to get the user list'

,

async

(

)

=>

{

   

const

response

=

await fetch

(

'/api/users'

)

;

   

const

data

=

await response.

json

(

)

;

   

    expect

(

response.

status

)

.

toBe

(

200

)

;

    expect

(

data.

success

)

.

toBe

(

true

)

;

    expect

(

Array

.

isArray

(

data.

data

)

)

.

toBe

(

true

)

;

 

}

)

;

 

  test

(

'should be able to create a new user'

,

async

(

)

=>

{

   

const

newUser

=

{

      name

:

"Test user"

,

      email

:

"test@example.com"

   

}

;

   

   

const

response

=

await fetch

(

'/api/users'

,

{

      method

:

'POST'

,

      headers

:

{

       

'Content-Type'

:

'application/json'

     

}

,

      body

:

JSON.

stringify

(

newUser

)

   

}

)

;

   

   

const

data

=

await response.

json

(

)

;

   

    expect

(

response.

status

)

.

toBe

(

201

)

;

    expect

(

data.

success

)

.

toBe

(

true

)

;

    expect

(

data.

data

.

name

)

.

toBe

(

newUser.

name

)

;

 

}

)

;

}

)

;