Post API Request using Playwright Java

Profile picture for user arilio666
Submitted by arilio666 on

In this article, we will make POST API requests using playwright java.

The same reqres site, solely for API testing, shall be used for this article for demonstration.

    Playwright playwright = Playwright.create();
        APIRequestContext request = playwright.request().newContext();

        Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
        Page page = browser.newPage();

        HashMap<String, String> data = new HashMap<String, String>();

        data.put("name", "Naruto");
        data.put("job", "Ninja");

        String response ="", RequestOptions.create().setData(data)).text();


        JsonObject j = new Gson().fromJson(response, JsonObject.class);
  • First, we create a request context and then access the post and other HTTP methods.
  • Before that, we generate a hashmap and set data according to the POST payload of the reqres site.
  • Then, we POST the payload to the respected URL using the request context.
  • Then using gson, a parser for getting JSON objects can be used to fetch the payload data.