4

In my Postman Mock Server, I have set up a GET request to return JSON, in which the following is returned

“due_date":"2021-10-10"

What I would like is to adjust the response so that the date is returned is two days in the past. So if today is “2021-10-10”, I would like the response to contain

“due_date":"2021-10-08”

And if today is “2022-01-01”, I would like the response to contain

“due_date":"2021-12-30”

And so on. How do I set up my Postman mock server request to return such data?

n-verbitsky
  • 552
  • 2
  • 9
  • 20
Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

0

I think it's a good question besides I'm curious so I made some research and found a workaround for this. It's a bit complex. I'm not sure worth it or not.

The first thing all, Postman Mock Server (in short Mock Server) cannot execute any test and pre-script so it is not capable to compute things. You need a calculation here so what are you gonna do? Well, you can define an environment for Mock Server which gives you the ability to use dynamic values in mock responses.

I will continue step by step to show the process.

1 - Open a Mock Server with an environment:

1.1 - Create a collection for the new Mock Server:

create-mock-server-1

Your mock response will look like below:

{"due_date": "{{date}}"}

1.2 - Create an environment:

create-mock-server-2

1.3 - Finish to create:

create-mock-server-3

1.4 - When you finish, Postman creates a collection like below:

create-mock-server-4

1.5 - You can test your Mock Server from this collection:

create-mock-server-5

As you can see, Mock Server uses the environment variable in their response.

Now, We have to figure out how to update the environment variable.

You have to use an external service to update your environment variable. You can use Postman Monitor for this job because it can execute tests (means any code) and works like a CRON job which means you can set a Postman Monitor to update a specific environment variable every 24 hours.

2 - Open a Postman Monitor to update your environment:

2.1 - This step is pretty straightforward, create a Postman Monitor like the below configuration:

create-postman-monitor-1

2.2 - Write a test to update the environment:

create-postman-monitor-2

The test will look like below:

// you have to use pm.test() otherwise Postman Monitor not execute the test
const moment = require("moment");

pm.test("update date", () => {
  // set date 2 days past
  let startdate = moment();
  const dayCount = 2;
  startdate = startdate.subtract(dayCount, "days");
  startdate = startdate.format("YYYY-MM-DD");

  // this is not work on Postman Monitor, use Postman API like below
  //pm.environment.set('date', startdate);

  const data = JSON.stringify({
    environment: {
      values: [
        {
          key: "date",
          value: startdate,
        },
      ],
    },
  });

  const environmentID = "<your-environment-id>";

  // Set environment variable with Postman API
  const postRequest = {
    url: `https://api.getpostman.com/environments/${environmentID}`,
    method: "PUT",
    header: {
      "Content-Type": "application/json",
      "X-API-Key":
        "<your-postman-api-key>",
    },
    body: {
      mode: "raw",
      raw: data,
    },
  };

  pm.sendRequest(postRequest, (error, response) => {
    console.log(error ? error : response.json());

    // force to fail test if any error occours
    if (error) pm.expect(true).to.equal(false);
  });
});

You cannot change an environment variable with pm.environment when you using Postman Monitor. You should use Postman API with pm.sendRequest in your test.

You need to get a Postman API key and you need to learn your environment id. You can learn the environment id from Postman API.

To learn your Environment ID, use this endpoint: https://www.postman.com/postman/workspace/postman-public-workspace/request/12959542-b7ace502-4a5a-4f1c-8164-158811bbf236

To learn how to get a Postman API key: https://learning.postman.com/docs/developer/intro-api/#generating-a-postman-api-key

2.3 - Run Postman Monitor manually to make sure tests are working:

create-postman-monitor-3

2.4 - As you can see Postman Monitor execute the script:

create-postman-monitor-4

2.5 - When I check the environment, I can see the result:

create-postman-monitor-5

You can test from browser to see results:

create-postman-monitor-6

ridvanaltun
  • 2,595
  • 2
  • 15
  • 28
  • All the code you provided beginning with "const moment = require("moment");", where does that live? – Dave Oct 13 '21 at 15:49
  • "Postman already knows what the moment module is so we don’t have to install this and save it anywhere, we are just basically telling the application that we’d like to make use of this within our test script." - https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/ – ridvanaltun Oct 13 '21 at 15:56
  • I'm not understanding where I place the code you provided on my mock server, even after reading through this link. I'm a newbie to using Postman as a mock server. – Dave Oct 13 '21 at 21:57
  • The post assume you know Postman Mock Server and Postman Monitor with no doubt therefore I accept it's hard to understand. I will try to make this post more informative in tomorrow. – ridvanaltun Oct 13 '21 at 22:10
  • 1
    Thanks for your thoughtful reply. The way we are using the Postman mock server right now is hitting the endpoints directly from our application in a test environment, so sadly, it is not realistic for the person using our application to run Postman monitor prior to using the application, although great to know thi sis an option! – Dave Oct 21 '21 at 15:48
0

I have answered this question earlier but I have another solution.

You can deploy a server to update the variable from your mock environment. If you want to do it for free, just use Heroku.

I wrote a Flask app in Python and deploy it to Heroku, check below code:

from flask import Flask
import os
import json
import requests
from datetime import datetime, timedelta

app = Flask(__name__)

# the port randomly assigned and then mapped to port 80 by the Heroku
port = int(os.environ.get("PORT", 5000))

# debug mode
debug = False


@app.route('/')
def hello_world():
    N_DAYS_AGO = 2

    # calculate date
    today = datetime.now()
    n_days_ago = today - timedelta(days=N_DAYS_AGO)
    n_days_ago_formatted = n_days_ago.strftime("%Y-%m-%d")

    # set environment
    payload = json.dumps({
        "environment": {
            "values": [
                {
                    "key": "occupation",
                    "value": n_days_ago_formatted
                }
            ]
        }
    })

    postman_api_key = "<your-postman-api-key>"

    headers = {
        'Content-Type': 'application/json',
        'X-API-Key': postman_api_key
    }

    environment_id = "<your-environment-id>"
    url = "https://api.getpostman.com/environments/" + environment_id

    r = requests.put(url, data=payload, headers=headers)

    # return postman response
    return r.content


if __name__ == '__main__':
    app.run(debug=debug, host='0.0.0.0', port=port)

Code calculates the new date and sends it to Mock Environment. It worked, I tested it in Heroku before this answer.

When you go to your Heroku app's page the code will trigger and the date environment automatically will update, use the environment variable in your mock server to solve the problem.

You need to automate this code execution so I suggest you use UptimeRobot to ping your Heroku app 1 time a day. On every ping, your environment variable will update. Don't overuse it because Heroku has a usage quota for the free plan.

To use this code you need to learn how to deploy a Flask app on Heroku. By the way, Flask is just an option here, you can use NodeJS instead of Python, the logic will stay the same.

ridvanaltun
  • 2,595
  • 2
  • 15
  • 28
  • Thanks but at this time, it is not an option to bring an additional vendor into our tech stack. – Dave Oct 25 '21 at 14:50