Can you run a java program from a Pre-request script?

I would like to do the following prior to every request in my entire Postman collection:

Fire off a “GET” request to see if my user has an entry in a cache

  • If user is not in cache ---->
    • run a Java program to generate a special value.
    • Fire of a “POST” with the special value to populate the cache.

Can this be done?

I’ve only seen our Pre-Request scripts using Javascript.

If you want to kick off some processing in Java, it sounds like you’d want to make that an endpoint in your API to kick off if an empty cache is returned which can be done in Postman using postman.setNextRequest in a conditional.

1 Like

Hi @nicholas.DiPiazza,

On the first part of your question, you can add Pre-Request scripts at the collection level as well, reference docs given below:
https://learning.getpostman.com/docs/postman/scripts/test_scripts/#adding-a-test-script-to-a-collection-or-folder
where you can fire off the “GET” request in the test script using pm.sendRequest as shown in the following docs and check if the value is expected: https://learning.getpostman.com/docs/postman/scripts/postman_sandbox_api_reference/#pmsendrequest

Example of a GET request using the above:

url = 'https://postman-echo.com/get'
pm.sendRequest(url, function (err, res) {
  if (err) { console.log(err); }
  pm.test('response should be okay to process', function () {
    pm.expect(err).to.equal(null);
    pm.expect(res).to.have.property('code', 200);
    pm.expect(res).to.have.property('status', 'OK');
  });
});
1 Like

Hi @nicholas.DiPiazza, you cannot directly run a Java program from your Postman collection. But you can expose a local server which executes the program when a particular endpoint is hit. You can then trigger that endpoint conditionally in your collection. For more details, see this thread:

4 Likes