You are currently viewing How to Use Network Interception in Playwright for Testing APIs

How to Use Network Interception in Playwright for Testing APIs

When we test applications, we often need to check how the app talks to the backend APIs. Network interception in Playwright helps us control and test these API calls. We can block requests, change responses, or check API data directly in our tests. This is very useful when the backend is slow, not ready, or when we want to test edge cases.

What Is Network Interception?

Network interception means Playwright can “catch” the request before it goes to the server. We can:

  • Block a request (like ads or third-party services).

  • Mock a response (send fake data back to the app).

  • Log or inspect requests (see headers, body, etc.).

This way, we don’t always depend on a real server for testing.

Example: Mocking an API Response

Here’s a simple Java example using Playwright:

page.route(“**/api/users”, route -> {
route.fulfill(new Route.FulfillOptions()
.setStatus(200)
.setContentType(“application/json”)
.setBody(“{\”users\”:[{\”id\”:1,\”name\”:\”Alice\”}]}”));
});

page.navigate(“https://example.com”);

// Now the frontend will think the API returned Alice, even if the real server is different

In this example:

  • We intercept all requests going to /api/users.

  • We return a custom response with a fake user Alice.

  • The frontend behaves as if the backend really returned this data.

Benefits of Network Interception

  • Test APIs without depending on the backend.

  • Create edge cases (like error codes 500, 404).

  • Speed up testing (no waiting for real server).

  • Increase reliability of tests (less flakiness).

Best Practices

  • Use real APIs for end-to-end tests, but interception for unit/functional tests.

  • Always log intercepted requests for debugging.

  • Combine interception with assertions to validate the frontend behavior.

Conclusion:
Network interception in Playwright makes API testing faster and more reliable. You can mock data, simulate errors, and test without waiting for real servers. This saves time, reduces flakiness, and helps you focus on testing the app’s behavior. By combining real API calls and interception, you can build strong and flexible automated tests.

 

Leave a Reply