Home > OS >  How to modify JSON response body with mitmproxy
How to modify JSON response body with mitmproxy

Time:12-07

When I send a request to a specific website API I get this as response

{
  "Tickets": [
    {
      "ticketAvailable": true,
...

How would I intercept and change ticketAvailable to false instead of true using mitmproxy?

from mitmproxy import ctx
from mitmproxy import http
import json

def response(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_url == "https://example.com/api/v1/something":
        data = json.loads(flow.response.get_text())
        data["data"]["Tickets"]["ticketAvailable"] = false
        flow.response.text = json.dumps(data)

I have tried this, but it doesn't seem to work.

EDIT: Have not managed to fix it yet

from mitmproxy import ctx
from mitmproxy import http
import json

def response(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_url == "https://example.com/api/v1/something":
        data = json.loads(flow.response.get_text())
        data["Tickets"][0]["ticketAvailable"] = "false"
        flow.response.text = json.dumps(data)

CodePudding user response:

Tickets is an array, so you'll need to access the 0th index in the array to update ticketAvailable to false. Also, there doesn't appear to be a data key in the response body, so there is no need for ["data"] when navigating the dictionary's keys.

Also note that booleans in Python are capitalised, i.e., True and False, so you should either use the native Python boolean (useful if you actually need to use data elsewhere) or wrap false in quotes (fine if you are just loading data back into JSON, which it looks like you are).

Either:

data["Tickets"][0]["ticketAvailable"] = False

Or:

data["Tickets"][0]["ticketAvailable"] = "false"

CodePudding user response:

I figured out a way to fix it. I simply changed flow.request.pretty_url to flow.request.pretty_url.endswith

from mitmproxy import ctx
from mitmproxy import http
import json

def response(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_url.endswith("/something"):
        data = json.loads(flow.response.get_text())
        data["Tickets"][0]["ticketAvailable"] = False
        flow.response.text = json.dumps(data)
  • Related