Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating requests Response content in Python

I'm new to Python. I'm trying to make a change in the Json body that I get in an exchange response using the requests library.

I want to do something like:

import json
import requests

def request_and_fill_form_in_response() -> requests.Response():
    response = requests.get('https://someurl.com')
    body_json = response.json()
    body_json['some_field'] = 'some_value'
    response.content = json.dumps(body_json)
    return response

In this particular scenario I'm only interested of updating the response.content object (regardless of if it is a good practice or not).

Is this possible?

(btw, the code above throws 'AttributeError: can't set attribute' error, which is pretty much self-explanatory, but I want to make sure I'm not missing something)

like image 843
Rodrigo Vaamonde Avatar asked Sep 05 '25 03:09

Rodrigo Vaamonde


1 Answers

You can rewrite the content in this way:

from json import dumps
from requests import get, Response


def request_and_fill_form_in_response() -> Response:
    response = get('https://mocki.io/v1/a9fbda70-f7f3-40bd-971d-c0b066ddae28')
    body_json = response.json()
    body_json['some_field'] = 'some_value'
    response._content = dumps(body_json).encode()
    return response


response = request_and_fill_form_in_response()

print(response.json())

and the result is: {'name': 'Aryan', 'some_field': 'some_value'}

but technically _content is a private variable and there must be a method as a setter to assign a value to it. Also, you can create your own Response object too. (you can check the response methods here)

like image 102
Aryan Arabshahi Avatar answered Sep 07 '25 20:09

Aryan Arabshahi