Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response' object is not subscriptable Python http post request

I am trying to post a HTTP request. I have managed to get the code to work but I am struggling returning some of the result.

The result looks like this

{   "requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",   "numberOfRequests" : 1893 } 

I am trying to get the requestId but I keep getting the error Response' object is not subscriptable

import json import requests  workingFile = 'D:\\test.json'  with open(workingFile, 'r') as fh:     data = json.load(fh)  url = 'http://jsontest' username = 'user' password = 'password123'  requestpost = requests.post(url, json=data, auth=(username, password))  print(requestpost["requestId"]) 
like image 293
tosh Avatar asked Dec 29 '15 10:12

tosh


People also ask

How do you fix an object is not Subscriptable in Python?

The TypeError: 'int' object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects. The issue can be resolved by removing any indexing or slicing to access the values of the integer object.

Why is set in Python not Subscriptable?

Set objects are unordered and are therefore not subscriptable.

What does type object is not Subscriptable mean in Python?

The “TypeError: 'type' object is not subscriptable” error is raised when you try to access an object using indexing whose data type is “type”. To solve this error, ensure you only try to access iterable objects, like tuples and strings, using indexing.

What data types are Subscriptable in Python?

In Python, strings, lists, tuples, and dictionaries fall in subscriptable category.


2 Answers

The response object contains much more information than just the payload. To get the JSON data returned by the POST request, you'll have to access response.json() as described in the example:

requestpost = requests.post(url, json=data, auth=(username, password)) response_data = requestpost.json() print(response_data["requestId"]) 
like image 155
Finwood Avatar answered Oct 12 '22 03:10

Finwood


You should convert your response to a dict:

requestpost = requests.post(url, json=data, auth=(username, password)) res = requestpost.json() print(res["requestId"]) 
like image 42
Pierre Michard Avatar answered Oct 12 '22 02:10

Pierre Michard