The error “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” can happen when you working with Python. Learn why Python raises this exception and how you can resolve it.
Reproduce The Error
Python provides a built-in module for encoding and decoding JSON contents, which can be strings or files. The loads()
is one of the most popular functions in this module. However, it raises a JSONDecodeError instead:
>>> import json
>>> json.loads(“”)
Traceback (most recent call last):
File “/usr/lib/python3.10/json/decoder.py”, line 355, in raw_decode
raise JSONDecodeError(“Expecting value”, s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
When you read an empty JSON file with load()
, Python will also print out a similar error message:
>>> import json
>>> with open("empty.json", "r") as emptyJSON:
... print(json.load(emptyJSON))
....
Traceback (most recent call last):
File "/usr/lib/python3.10/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2)
You can run into this error outside the json module as well. Requests is a popular library for dealing with HTTP requests in Python. It supports the json()
method, which converts the fetched content from a resource URI into a JSON object. But it can unexpectedly raise the JSONDecodeError exception:
>>> import requests
>>> URL="http://httpbin.org/status/200"
>>> response = requests.delete(URL)
>>> print(response.json())
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
…
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Explain The Error
The first two examples are obvious. The error message is displayed in those cases because you provide load()
and loads()
with empty JSON content.
When those methods fail to deserialize and parse a valid JSON document from those sources, they raise the JSONDecodeError exception.
From this clue, we can guess why the response.json()
method in the third example also produces the same error.
There is a high chance the response object itself is empty. This is indeed true, which can be verified by using response.text
to get the content of the response:
This is a common response message when we send an HTTP DELETE request to delete a resource. This can be the case even with the status code 200 (meaning the deleting action has been carried out).
Solutions
Refraining from parsing empty files and strings as JSON documents is an obvious fix. But in many situations, we can’t control whether a data source can be empty or not.
Python, however, allows us to handle exceptions like JSONDecodeError. For instance, you can use the try-catch
statements below to prevent error messages in the case of empty strings and files:
Example 1
try: json.loads("") except json.decoder.JSONDecodeError: print("")
Example 2
try: with open("empty.json", "r") as emptyJSON: print(json.load(emptyJSON)) except json.decoder.JSONDecodeError: print("")
Those snippets execute the loads()
and load()
functions. If the JSONDecodeError exception is raised, Python executes the except
clause and prints an empty string instead of an error message.
We can apply the same idea when parsing the content of an HTTP request response:
try: URL = "http://httpbin.org/status/200" response = requests.delete(URL) print(response.json()) except requests.exceptions.JSONDecodeError: print("")
It is important to note that you must change the exception to catch from json.decoder.JSONDecodeError
to requests.exceptions.JSONDecodeError
.
Summary
Python throws the error “JSONDecodeError: Expecting value: line 1 column 1 (char 0)” when it parses an empty string or file as JSON. You can use a try
statement to catch
and handle this exception.
Maybe you are interested in similar errors:
- DataFrame constructor not properly called!
- ModuleNotFoundError: No module named ‘tensorflow’ in python
- ModuleNotFoundError: No module named ‘scipy’ in Python
- RuntimeError: dictionary changed size during iteration
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python
пытаюсь получить ответ смог ли я авторизироваться но выдает ошибку
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Сам код:
import requests
import json
data = {"authentication_type": "password",
"username": "sdgdfre@gmail.com",
"password": "saefewfwef34wef",
"client_id": "71a7beb8-f21a-47d9-a604-2e71bee24fe0",
"session_id": "81150f95-0283-4f28-80ce-39af462cb0e7",
"nection": "keep-alive",
"Content-Length": "3506",
"Cookie": "bm_sz=51FB8A6E49797D348FD8C30B29DBC889~YAAQJIQUAjT+ZjZxAQAAdhBmVgcW7BW8DtG3YOzVK00BtoPxyPJGa75kqt6ZHaSYFjHAxHFG5jYYXUJKjh0ACWdThJ2bIkRg3n9hDGSp1SQjj3L1QbQglPpvdP1sP+M3YX3RKwznJpGMQDTE7vWKXW8ua3NhLMR02MjRU73Y9+9wvfTTBzYjUaOUtY/7LjFRHBZP+SgTc6sX288iRz4hEOfQ; s_fid=69469C67FE887F9D-22D6724693954A9B; s_cc=true; ndcd=wc1.1.w-729460.1.2.DoAhAcoc59z6LOEx1i5nZQ%252C%252C.ip_xUgwzDza_KazLpD4k_kp9N-EuBZTdiPNIGfTf_lmts6dKetsy9CSPz7bq9GpTXaMqvv5nsFxMoR0NMX87oDcrScghLo0TDXUoP59_UwrtppgjzuzUn0SsIEXNcyGhEHRUjPpSaB0e9oUtPu8p37toCGkD-fYUKVqrk0db-16vFXHoUUrHY0MZ07MQPFVc; _abck=B3D11D3B9652858D3F6BB8A76EA7977D~0~YAAQj08VAgnbkRxxAQAACBp0VgNDEYIloNj7CgJagNJjRvVAAcUVONWT0mOQiz2H6BGfRiHg6q5O4Ocv0Ff40vT3M61rUzZ/Oj7O3vRUtPggHC/xBVtUuR41oWLHR3092j5mkPLaKkLc56oVze4uf+SEj7kYdxUs5NfURu5ckrY2w4sBMm70Uk90krmLjmoVLq7zqJVnxK26YCIyCoUYmXjUP3MA1fmhHjUgBwvP1XeXjkxVs4Sip0vuH0wweBK5whIxgTSvHAbJS3beXMVcKRe8rWLNY7Rd1uMURjisvLfospoYMmOuY1/AZnVFO+G+X29JgFKJMRjKE3Mm3y18BqTfRtioMNdA1A==~-1~-1~-1; s_sq=snepdrglobal%3D%2526c.%2526a.%2526activitymap.%2526page%253Dhttps%25253A%25252F%25252Fid.sonyentertainmentnetwork.com%25252Fsignin%25252F%25253Fresponse_type%25253Dxxxx%252526redirect_uri%25253Dxxxxx%2525259x%2525259x%2525259xxxxxx.xxxxxxxxxxx.xxx%2525259xxx-xx%2525259xxxxx%2525259xxxxxx-xxx99999-xxxxxxxxxxxxxxxx%252526client_id%25253Dx9x9999x-x999-9999-99x9-9999999999x9%252526scope%25253Dxxxxxx%2525259xxxxxxxxx_xxxxxx%2525259xxxxxxx%2525259xx%2526link%253D%2525D0%252592%2525D0%2525BE%2525D0%2525B9%2525D1%252582%2525D0%2525B8%252520%2525D0%2525B2%252520%2525D1%252581%2525D0%2525B5%2525D1%252582%2525D1%25258C%2526region%253Dember24%2526.activitymap%2526.a%2526.c",
"Content-Type": "application/json; charset=UTF-8",
'widget_data': '{"jvqtrgQngn":{"oq":"1496:723:1536:824:1536:824","wfi":"flap-139108","oc":"9nr12s5s7sqq2osp","fe":"1536k864 24","qvqgm":"-240","jxe":755748,"syi":"gehr","si":"si,btt,zc4,jroz","sn":"sn,zcrt,btt,jni","us":"7os1q32n7n2qp24q","cy":"Jva32","sg":"{"zgc":0,"gf":snyfr,"gr":snyfr}","sp":"{"gp":gehr,"ap":gehr}","sf":"gehr","jt":"s2nno0055p58o750","sz":"r0rq67ss2747oq0o","vce":"apvc,0,5r8pr752,2,1;fg,0,rzore19,0,rzore22,0;zz,4q65s,443,6,wf-FVRJF1yvo-urnqre-Pbagrag;gf,0,4q65s;zzf,3r9,0,n,42 0,331q 5580,153n,155r,-34898,1n0pp,-6spp;zzf,3r9,3r9,n,41 0,41 74,2p,2p,-507,2n8,-41;zzf,3r9,3r9,n,41 0,13s 0,2q,2r,-284,p37,139;xx,18r,0,rzore19;ss,0,rzore19;zp,53,2r0,182,rzore19;xq,67;xq,11;xq,94;xq,87;zzf,72,3r6,n,0 73,99n rp,282,27o,-58q7,47o2,202;xq,15;xq,8n;xq,64;zz,1s,2pn,189,rzore19;xq,217;xq,90;zzf,20,3r9,n,41 0,1p3 r5,o0,o0,-rnr,94p,-312;xq,212;zzf,1q5,3r7,n,ABC;xq,nq;xq,70;xq,1o8;xq,81;xq,70;zzf,22,3r8,n,ABC;xq,p1;xq,s0;xq,6r;xq,80;xq,9o;xq,n5;so,9,rzore19;xx,2,0,rzore22;ss,0,rzore22;zzf,1,3ro,n,ABC;xq,156;xq,2s;xq,no;xq,78;xq,p3;xq,3;zzf,77,3r5,n,ABC;xq,29;xq,45;xq,7;xq,7p;xq,5o;xq,2;zz,21,2p3,190,rzore22;xq,13;xq,n;xq,33;zzf,228,3r7,n,0 2o0,81 12pq,4q1,4q0,-9362,90on,on9;xq,105;xq,88;xq,66;so,159,rzore22;zz,22r7,268,1s6,;gf,0,523n2;zzf,r0,2713,32,21 3n,10no 26n,111,np4,-4nn4,51os,3r;xx,218,s,rzore22;ss,0,rzore22;so,n,rzore22;zp,5s,304,1p1,;zzf,2490,2711,32,0 3n,928 nn0,q5,84o,-3q40,44sp,-17p;zz,23oq,378,69,;gf,0,56s50;zzf,353,2710,32,417 5nr,1o13 55rp,1s1,1380,-1n189,1p035,-16;zzf,270s,270s,32,ABC;zzf,2710,2710,32,ABC;gf,0,5p0p2;zzf,2710,2710,32,ABC;zz,3r78,38r,93,;gf,0,6264n;zz,213p,50n,61,;zzf,8nns,rn63,1r,142 68,5rq 74,5n,1532,-2s9,24s,0;gf,0,6q235;zzf,rn60,rn60,1r,ABC;gf,0,7op95;zz,5qo2,228,13,wf-FVRJF1yvo-urnqre-RkcynvaGrkg;gf,0,81n47;zzf,8pnr,rn60,1r,0 2p9,735 2p1,5n,1506,-278,3qn,0;gf,0,8n6s5;zzf,rn60,rn60,1r,ABC;gf,0,99155;zzf,rn60,rn60,1r,ABC;gf,0,n7oo5;zz,p5qr,463,48,;gf,0,o4193;zz,12984,394,4,wf-FVRJF1yvo-urnqre-Pbagrag;gf,0,p6o17;zz,34n10,368,92,;gf,0,so527;zz,50qqr,399,8,wf-FVRJF1yvo-urnqre-Pbagrag;gf,0,14p305;zz,10896,348,8s,;gf,0,15po9o;zz,sr54,3po,3,wf-FVRJF1yvo-urnqre-PbagragNern;gf,0,16p9rs;zz,1s68,3o1,8o,;zz,r2n0,41r,7,wf-FVRJF1yvo-urnqre-Pbagrag;gf,0,17pos7;zz,3s06,3oo,1o,wf-FVRJF1yvo-urnqre-RkcynvaGrkg;gf,0,180nsq;zp,812,4o5,46,;zp,3q1,54o,17,wf-FVRJF1yvo-urnqre-PybfrVpba;zz,614,424,4n,;zz,607n5,411,2,;gf,0,1r2499;zz,1rnn,3p,175,;xx,1q8,0,rzore22;ss,0,rzore22;zp,67,254,102,rzore22;xq,2n;xq,7o;xq,106;xq,65;xq,3;xq,60;xq,41;xq,46;xq,25;xq,22;xq,46;so,102,rzore22;zp,59,2np,148,;zz,235r,3oq,59,;gf,0,1r6qp2;zp,q88,313,139,;zz,285,407,1rs,;zz,qrr8,50r,103,;gf,0,1s5po7;zz,162o1,2p1,s7,rzore22;gf,0,20os68;xx,527,0,rzore22;ss,0,rzore22;zp,21q,330,180,;so,251,rzore22;xx,3s7,0,rzore22;ss,0,rzore22;zp,7n,2s3,10n,rzore22;zz,221,2rs,104,rzore22;xq,43;xq,83;xq,qs;xq,pq;xq,p9;xq,ro;xq,p3;so,11p,rzore22;zp,67,2q3,141,;zz,q0p,5p2,10q,;","ns":""},"jg":"1.j-666234.1.2.D5OvqtaS7GCnmmrmC2-V5N,,.b8CsKg70ZJDbDPfA4qG1quWTyOnsHd4QZ6-P6UFljHyqxgCBTjpjEkiGcfcRqc7pAf4tkSsDx_5SBjm2TiI7wz2-Lk07sjT3fryAS7s0o6xezR9mfNsxpAC7RV6NnmBoJbcbuAQ0P1hdlZaQdAabIBhoYZLPMyp_FG5a52ZeBHjtxdS61bi8P6eOGUgMmW1RmmB24xOhU2nrIH3p3GCDl1Y8R51YTwn7d5sadu_O1z2dhH_TR8GJHUOyxrTk6_f7"}'}
hea = {"Accept": "*/*",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 OPR/67.0.3575.115 (Edition Yx)",
"Accept-Encoding":'gzip, deflate, br',
"Accept-Language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7",
"ost": "auth.api.sonyentertainmentnetwork.com",
"Referer": "https://id.sonyentertainmentnetwork.com /",
"X-Origin-ClientId": "f6c7057b-f688-4744-91c0-8179592371d2",
"X-Referer-Info": "https://id.sonyentertainmentnetwork.com/signin/?response_type=code&redirect_uri=https%3A%2F%2Fstore.playstation.com%2Fru-ru%2Fhome%2FSTORE-MSF75508-MOBHOMEGAMESONLY&client_id=f6c7057b-f688-4744-91c0-8179592371d2&prompt=login&state=returning&request_locale=ru_RU&service_entity=urn%3Aservice-entity%3Apsn&hidePageElements=SENLogo&disableLinks=SENLink&ui=pr&error=login_required&error_code=4165&error_description=User+is+not+authenticated&no_captcha=false"}
s = requests.Session()
r = s.post('https://id.sonyentertainmentnetwork.com/signin/?response_type=code&redirect_uri=https%3A%2F%2Fstore.playstation.com%2Fru-ru%2Fhome%2FSTORE-MSF75508-MOBHOMEGAMESONLY&client_id=f6c7057b-f688-4744-91c0-8179592371d2&scope=kamaji%3Acommerce_native%2Ckamaji%3Acommerce_container%2Ckamaji%3Alists&prompt=login&state=returning&request_locale=ru_RU&service_entity=urn%3Aservice-entity%3Apsn&hidePageElements=SENLogo&disableLinks=SENLink&ui=pr&error=login_required&error_code=4165&error_description=User+is+not+authenticated&no_captcha=false#/signin?entry=%2Fsignin',data=data,headers=hea)
r2 = json.loads(r.text)
print(r2['message'])
I have reproduced this with requests v. 2.18.4 and 2.14.2, along with Python 3.6.1 and 3.6.2. I have used my system-installed Python/requests (macOS Sierra with Python 3.6.1 downloaded from python.org), Python / requests installed as part of conda 4.3.25, and the latest Python and requests installed from conda-forge.
Same results everywhere.
Expected Result
Expected to see a dictionary of JSON values, as indicated here: http://docs.python-requests.org/en/master/
Actual Result
Python interpreter crashes.
Reproduction Steps
Python 3.6.2 | packaged by conda-forge | (default, Jul 23 2017, 23:01:38)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://pypi.python.org/pypi')
>>> r.status_code
200
>>> r.encoding
'utf-8'
>>> r.json()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/site-packages/requests/models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
System Information
$ python -m requests.help
{
"chardet": {
"version": "3.0.4"
},
"cryptography": {
"version": "2.0.3"
},
"idna": {
"version": ""
},
"implementation": {
"name": "CPython",
"version": "3.6.2"
},
"platform": {
"release": "16.7.0",
"system": "Darwin"
},
"pyOpenSSL": {
"openssl_version": "100020cf",
"version": "17.2.0"
},
"requests": {
"version": "2.18.4"
},
"system_ssl": {
"version": "100020cf"
},
"urllib3": {
"version": "1.22"
},
"using_pyopenssl": true
}
Eager to get started? This page gives a good introduction in how to get started
with Requests.
First, make sure that:
- Requests is installed
- Requests is up-to-date
Let’s get started with some simple examples.
Make a Request¶
Making a request with Requests is very simple.
Begin by importing the Requests module:
Now, let’s try to get a webpage. For this example, let’s get GitHub’s public
timeline:
>>> r = requests.get('https://api.github.com/events')
Now, we have a Response
object called r
. We can
get all the information we need from this object.
Requests’ simple API means that all forms of HTTP request are as obvious. For
example, this is how you make an HTTP POST request:
>>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})
Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
OPTIONS? These are all just as simple:
>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'}) >>> r = requests.delete('https://httpbin.org/delete') >>> r = requests.head('https://httpbin.org/get') >>> r = requests.options('https://httpbin.org/get')
That’s all well and good, but it’s also only the start of what Requests can
do.
Passing Parameters In URLs¶
You often want to send some sort of data in the URL’s query string. If
you were constructing the URL by hand, this data would be given as key/value
pairs in the URL after a question mark, e.g. httpbin.org/get?key=val
.
Requests allows you to provide these arguments as a dictionary of strings,
using the params
keyword argument. As an example, if you wanted to pass
key1=value1
and key2=value2
to httpbin.org/get
, you would use the
following code:
>>> payload = {'key1': 'value1', 'key2': 'value2'} >>> r = requests.get('https://httpbin.org/get', params=payload)
You can see that the URL has been correctly encoded by printing the URL:
>>> print(r.url) https://httpbin.org/get?key2=value2&key1=value1
Note that any dictionary key whose value is None
will not be added to the
URL’s query string.
You can also pass a list of items as a value:
>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']} >>> r = requests.get('https://httpbin.org/get', params=payload) >>> print(r.url) https://httpbin.org/get?key1=value1&key2=value2&key2=value3
Response Content¶
We can read the content of the server’s response. Consider the GitHub timeline
again:
>>> import requests >>> r = requests.get('https://api.github.com/events') >>> r.text u'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests will automatically decode content from the server. Most unicode
charsets are seamlessly decoded.
When you make a request, Requests makes educated guesses about the encoding of
the response based on the HTTP headers. The text encoding guessed by Requests
is used when you access r.text
. You can find out what encoding Requests is
using, and change it, using the r.encoding
property:
>>> r.encoding 'utf-8' >>> r.encoding = 'ISO-8859-1'
If you change the encoding, Requests will use the new value of r.encoding
whenever you call r.text
. You might want to do this in any situation where
you can apply special logic to work out what the encoding of the content will
be. For example, HTML and XML have the ability to specify their encoding in
their body. In situations like this, you should use r.content
to find the
encoding, and then set r.encoding
. This will let you use r.text
with
the correct encoding.
Requests will also use custom encodings in the event that you need them. If
you have created your own encoding and registered it with the codecs
module, you can simply use the codec name as the value of r.encoding
and
Requests will handle the decoding for you.
Binary Response Content¶
You can also access the response body as bytes, for non-text requests:
>>> r.content b'[{"repository":{"open_issues":0,"url":"https://github.com/...
The gzip
and deflate
transfer-encodings are automatically decoded for you.
For example, to create an image from binary data returned by a request, you can
use the following code:
>>> from PIL import Image >>> from io import BytesIO >>> i = Image.open(BytesIO(r.content))
JSON Response Content¶
There’s also a builtin JSON decoder, in case you’re dealing with JSON data:
>>> import requests >>> r = requests.get('https://api.github.com/events') >>> r.json() [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
In case the JSON decoding fails, r.json()
raises an exception. For example, if
the response gets a 204 (No Content), or if the response contains invalid JSON,
attempting r.json()
raises ValueError: No JSON object could be decoded
.
It should be noted that the success of the call to r.json()
does not
indicate the success of the response. Some servers may return a JSON object in a
failed response (e.g. error details with HTTP 500). Such JSON will be decoded
and returned. To check that a request is successful, use
r.raise_for_status()
or check r.status_code
is what you expect.
Raw Response Content¶
In the rare case that you’d like to get the raw socket response from the
server, you can access r.raw
. If you want to do this, make sure you set
stream=True
in your initial request. Once you do, you can do this:
>>> r = requests.get('https://api.github.com/events', stream=True) >>> r.raw <urllib3.response.HTTPResponse object at 0x101194810> >>> r.raw.read(10) 'x1fx8bx08x00x00x00x00x00x00x03'
In general, however, you should use a pattern like this to save what is being
streamed to a file:
with open(filename, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk)
Using Response.iter_content
will handle a lot of what you would otherwise
have to handle when using Response.raw
directly. When streaming a
download, the above is the preferred and recommended way to retrieve the
content. Note that chunk_size
can be freely adjusted to a number that
may better fit your use cases.
Note
An important note about using Response.iter_content
versus Response.raw
.
Response.iter_content
will automatically decode the gzip
and deflate
transfer-encodings. Response.raw
is a raw stream of bytes – it does not
transform the response content. If you really need access to the bytes as they
were returned, use Response.raw
.
More complicated POST requests¶
Typically, you want to send some form-encoded data — much like an HTML form.
To do this, simply pass a dictionary to the data
argument. Your
dictionary of data will automatically be form-encoded when the request is made:
>>> payload = {'key1': 'value1', 'key2': 'value2'} >>> r = requests.post("https://httpbin.org/post", data=payload) >>> print(r.text) { ... "form": { "key2": "value2", "key1": "value1" }, ... }
The data
argument can also have multiple values for each key. This can be
done by making data
either a list of tuples or a dictionary with lists
as values. This is particularly useful when the form has multiple elements that
use the same key:
>>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')] >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples) >>> payload_dict = {'key1': ['value1', 'value2']} >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict) >>> print(r1.text) { ... "form": { "key1": [ "value1", "value2" ] }, ... } >>> r1.text == r2.text True
There are times that you may want to send data that is not form-encoded. If
you pass in a string
instead of a dict
, that data will be posted directly.
For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:
>>> import json >>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, data=json.dumps(payload))
Instead of encoding the dict
yourself, you can also pass it directly using
the json
parameter (added in version 2.4.2) and it will be encoded automatically:
>>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, json=payload)
Note, the json
parameter is ignored if either data
or files
is passed.
Using the json
parameter in the request will change the Content-Type
in the header to application/json
.
POST a Multipart-Encoded File¶
Requests makes it simple to upload Multipart-encoded files:
>>> url = 'https://httpbin.org/post' >>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files) >>> r.text { ... "files": { "file": "<censored...binary...data>" }, ... }
You can set the filename, content_type and headers explicitly:
>>> url = 'https://httpbin.org/post' >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} >>> r = requests.post(url, files=files) >>> r.text { ... "files": { "file": "<censored...binary...data>" }, ... }
If you want, you can send strings to be received as files:
>>> url = 'https://httpbin.org/post' >>> files = {'file': ('report.csv', 'some,data,to,sendnanother,row,to,sendn')} >>> r = requests.post(url, files=files) >>> r.text { ... "files": { "file": "some,data,to,send\nanother,row,to,send\n" }, ... }
In the event you are posting a very large file as a multipart/form-data
request, you may want to stream the request. By default, requests
does not
support this, but there is a separate package which does —
requests-toolbelt
. You should read the toolbelt’s documentation for more details about how to use it.
For sending multiple files in one request refer to the advanced
section.
Warning
It is strongly recommended that you open files in binary
mode. This is because Requests may attempt to provide
the Content-Length
header for you, and if it does this value
will be set to the number of bytes in the file. Errors may occur
if you open the file in text mode.
Response Status Codes¶
We can check the response status code:
>>> r = requests.get('https://httpbin.org/get') >>> r.status_code 200
Requests also comes with a built-in status code lookup object for easy
reference:
>>> r.status_code == requests.codes.ok True
If we made a bad request (a 4XX client error or 5XX server error response), we
can raise it with
Response.raise_for_status()
:
>>> bad_r = requests.get('https://httpbin.org/status/404') >>> bad_r.status_code 404 >>> bad_r.raise_for_status() Traceback (most recent call last): File "requests/models.py", line 832, in raise_for_status raise http_error requests.exceptions.HTTPError: 404 Client Error
But, since our status_code
for r
was 200
, when we call
raise_for_status()
we get:
>>> r.raise_for_status() <Response [200]>
All is well.
Note
raise_for_status
returns the response object for a successful response. This eases chaining in trivial cases, where we want bad codes to raise an exception, but use the response otherwise:
>>> value = requests.get('http://httpbin.org/ip').raise_for_status().json()['origin']
Cookies¶
If a response contains some Cookies, you can quickly access them:
>>> url = 'http://example.com/some/cookie/setting/url' >>> r = requests.get(url) >>> r.cookies['example_cookie_name'] 'example_cookie_value'
To send your own cookies to the server, you can use the cookies
parameter:
>>> url = 'https://httpbin.org/cookies' >>> cookies = dict(cookies_are='working') >>> r = requests.get(url, cookies=cookies) >>> r.text '{"cookies": {"cookies_are": "working"}}'
Cookies are returned in a RequestsCookieJar
,
which acts like a dict
but also offers a more complete interface,
suitable for use over multiple domains or paths. Cookie jars can
also be passed in to requests:
>>> jar = requests.cookies.RequestsCookieJar() >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies') >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere') >>> url = 'https://httpbin.org/cookies' >>> r = requests.get(url, cookies=jar) >>> r.text '{"cookies": {"tasty_cookie": "yum"}}'
Redirection and History¶
By default Requests will perform location redirection for all verbs except
HEAD.
We can use the history
property of the Response object to track redirection.
The Response.history
list contains the
Response
objects that were created in order to
complete the request. The list is sorted from the oldest to the most recent
response.
For example, GitHub redirects all HTTP requests to HTTPS:
>>> r = requests.get('http://github.com/') >>> r.url 'https://github.com/' >>> r.status_code 200 >>> r.history [<Response [301]>]
If you’re using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
redirection handling with the allow_redirects
parameter:
>>> r = requests.get('http://github.com/', allow_redirects=False) >>> r.status_code 301 >>> r.history []
If you’re using HEAD, you can enable redirection as well:
>>> r = requests.head('http://github.com/', allow_redirects=True) >>> r.url 'https://github.com/' >>> r.history [<Response [301]>]
Timeouts¶
You can tell Requests to stop waiting for a response after a given number of
seconds with the timeout
parameter. Nearly all production code should use
this parameter in nearly all requests. Failure to do so can cause your program
to hang indefinitely:
>>> requests.get('https://github.com/', timeout=0.001) Traceback (most recent call last): File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
Note
timeout
is not a time limit on the entire response download;
rather, an exception is raised if the server has not issued a
response for timeout
seconds (more precisely, if no bytes have been
received on the underlying socket for timeout
seconds). If no timeout is specified explicitly, requests do
not time out.
Errors and Exceptions¶
In the event of a network problem (e.g. DNS failure, refused connection, etc),
Requests will raise a ConnectionError
exception.
Response.raise_for_status()
will
raise an HTTPError
if the HTTP request
returned an unsuccessful status code.
If a request times out, a Timeout
exception is
raised.
If a request exceeds the configured number of maximum redirections, a
TooManyRedirects
exception is raised.
All exceptions that Requests explicitly raises inherit from
requests.exceptions.RequestException
.
Ready for more? Check out the advanced section.
If you’re on the job market, consider taking this programming quiz. A substantial donation will be made to this project, if you find a job through this platform.