Using mitmproxy reverse mode for API testing

mitmproxy is my preferred proxy for API testing these days. I’m using it mostly in reverse mode though, so I thought I’d capture my setup in case it’s useful for anyone else. My main use case is to inspect the traffic coming into the API server and being returned, mostly when running tests against it. Where mitmproxy is typically used as a proxy to monitor traffic passing into/out of a client application, for this I’m concerned with the server’s handling. Reverse mode lets me inspect and adjust the traffic as I go along. I start up the proxy, configure the tests to point to it instead of the actual server, and I’m all set.

Start reverse proxy mode

Mitmproxy has a great web UI as well but as a keyboard-only user, I just use the terminal tools – pick what works best for you, but these instructions are CLI-based.

Start the reverse proxy and tell it where to send traffic onward to; in this example the API I’m calling is on http://localhost:3000

mitmproxy --mode reverse:http://localhost:3000

By default the server listens on port 8080 and forwards everything.

Configure the application

In my use case, I’m adjusting the API tests to point to the proxy instead of the actual server so I can capture, replay, and/or adjust the traffic when I’m working with the tests.

I configure my tests to test an API at http://localhost:8080 (actually I’m running bits of this in docker so it ends up being http://host.docker.internal:8080 but this is more of a note to future-me than general advice!)

That’s all. Start using the application and you should start to see the requests and responses showing up in mitmproxy.

Additional notes and tricks

From the logged traffic records, you can replay, duplicate, and edit requests, which is great for testing and inspecting anything that’s not trivial to reproduce.

You can also use mitmproxy add-ons to rewrite responses if you need to. I use this feature to throw unexpected responses (that the API should never actually produce) back at the tests to make sure they do fail when they should!

To save a flow, either to share or to come back to later on, press w and provide a filename. Then load it in a future mitmproxy session using a command like mitmproxy -r flows.mitm.

Add a comment if you have additional experiences to share, I’m always excited to learn some new tricks to add to my collection!

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)