API Testing với Postman (Phần 27) – Lưu response body dưới dạng file csv

Đây là 1 câu hỏi mình từng trả lời trên stackoverflow, bây giờ mình viết lại thành 1 bài hướng dẫn để phục vụ cho sau này.

I. Problem

Mình có 1 response như sau:

{
  "results": [
    {
      "jobId": 44137966,
      "employerId": 575264,
      "employerName": "REED",
      "employerProfileId": null
    },
    {
      "jobId": 1111,
      "employerId": 57523232264,
      "employerName": "EEEE",
      "employerProfileId": null
    }
  ]
}

Bây giờ mình muốn lưu thông tin trên dưới dạng csv, có hình dạng như sau:

jobId,employerId,employerName,employerProfileId
44137966,575264,REED,null
1111,57523232264,EEEE,null

II. Solution

Do postman không có chức năng này, nên chúng ta chỉ có cách là phải tạo ra 1 App đọc json và save thành csv file. Ở đây mình chọn App dạng nodejs vì nó đơn giản.

1. Mô tả cách xử lý vấn đề

  1. Từ postman ta gửi request như bình thường
  2. Server sẽ trả lại response
  3. Lấy response ở trên gửi vào App ở localhost
  4. App sẽ đọc và lưu thông tin vào file csv
  5. App trả lại thông tin là có lưu thông tin thành công hay ko

2. Tạo app bằng nodejs

  • Đầu tiên, cần cài Nodejs vào máy trước. https://nodejs.org/en/download/
  • Clone project https://github.com/sivcan/ResponseToFile-Postman bằng git
    git clone https://github.com/sivcan/ResponseToFile-Postman
  • Mở file script.js trong project vừa down về, copy đoạn code dưới đây, đặt vào cuối file.
const converter = require("json-2-csv");

app.post("/toCsv", (req, res) => {
    let filename = `File_${Date.now()}`,
        filePath = `${path.join(folderPath, filename)}.csv`;

    converter.json2csv(req.body, (err, csv) => {
        fs.writeFileSync(filePath, csv);
        if (err) {
            console.log(err);
            res.send("Error");
        } else {
            res.send("Success");
        }
    });
});
  • Mở powershell/cmd rồi cd vào folder project, ví dụ:
  • Run npm i (download các thư viện cần thiết cho project)
  • Run node --no-warnings .\script.js để start App

3. Viết phần tạo request trong postman test

Mở tab Tests trên postman và điền đoạn code dưới đây:

const list = pm.response.json().results;

const postRequest = {
  url: 'http://localhost:3000/toCsv',
  method: 'POST',
  header: {
    'Content-Type': 'application/json',
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify(list)
  }
};
pm.sendRequest(postRequest, (error, response) => {
  console.log(error ? error : response);
});
enter image description here

Lưu ý: request body của request này phải là Array của các object nhé.

III. Test thử nghiệm.

Nếu bạn nào cần test thử, bạn có thể import curl vào postman:

curl --location --request POST 'https://auto-test-challenges.herokuapp.com/echo' \
--header 'Content-Type: application/json' \
--data-raw '{
  "results": [
    {
      "jobId": 44137966,
      "employerId": 575264,
      "employerName": "REED",
      "employerProfileId": null
    },
    {
      "jobId": 1111,
      "employerId": 57523232264,
      "employerName": "EEEE",
      "employerProfileId": null
    }
  ]
}'

IV. Tổng kết

Project mẫu mà mình dùng ở trên là mình lấy ở trên mạng, mình chỉ viết thêm 1 chút ít để phù hợp cho nhu cầu. Hi vọng bài viết có ích cho bạn nào cần, nếu cần hỏi gì đó hãy để lại comment nhé. Thanks

5 3 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments