data = {
'ids': [12, 3, 4, 5, 6 , ...]
}
urllib2.urlopen("http://abc.example/api/posts/create",urllib.urlencode(data))
I want to send a POST request, but one of the fields should be a list of numbers. How can I do that? (JSON?)
data = {
'ids': [12, 3, 4, 5, 6 , ...]
}
urllib2.urlopen("http://abc.example/api/posts/create",urllib.urlencode(data))
I want to send a POST request, but one of the fields should be a list of numbers. How can I do that? (JSON?)
If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...
Python 2.x
import json
import urllib2
data = {
'ids': [12, 3, 4, 5, 6]
}
req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Python 3.x
https://mcmap.net/q/174164/-how-do-i-send-a-post-request-as-a-json
If you don't specify the header, it will be the default application/x-www-form-urlencoded
type.
add_header()
again, for each header you want to add. –
Curtice req = urllib.Request('http://uat-api.synapsefi.com') req.add_header('X-SP-GATEWAY', 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv') req.add_header('X-SP-USER-IP', '127.0.0.1') req.add_header('X-SP-USER', '| ge85a41v8e16v1a618gea164g65') req.add_header('Content-Type', 'application/json') print(req)
... –
Banlieue The view tab.views.profileSetup didn't return an HttpResponse object. It returned None instead.
@Curtice –
Banlieue import urllib.request
and urllib.request.Request()
. Furthermore, printing the req object does nothing interesting. You can clearly see the headers have been added by printing req.headers
. Beyond that, I am not sur why it isn't working in your application. –
Curtice response = urllib.request.Request(req, json.dumps(data))
and req = urllib.request.Request('http://uat-api.synapsefi.com')
. i am getting a message saying unknown url type: 'urllib.request.Request object at 0x00000250B05474A8'
from the second line that i made changes to... what is the way fro me to change the url type @Curtice –
Banlieue urlopen()
like the original example. That is why you are getting an error. See: pastebin.com/1gUdGYcP –
Curtice POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
–
Banlieue I recommend using the incredible requests
module.
http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
TypeError: post() takes from 1 to 2 positional arguments but 3 were given
–
Lamarckism json=payload
(which may have been introduced since this answer was written long ago) without specifying the header or calling json.dumps()
. See other answers on this page. –
Sharlenesharline For python 3.4.2, I found the following will work:
import urllib.request
import json
body = {'ids': [12, 14, 50]}
myurl = "http://www.testmycode.example"
req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
Content-Length
header, it will be calculated by urllib
automatically. –
Sharlenesharline This works perfect for Python 3.5
, if the URL contains Query String / Parameter value,
Request URL = https://bah2.example/ws/rest/v1/concept/
Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca
import requests
url = 'https://bahbah2.example/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), json=data)
print(r.status_code)
verify=False
, which disables certificate validation and opens your code up to man-the-middle attacks. –
Sharlenesharline verify=False
from the code sample to resolve the above comment. –
Sharlenesharline Here is an example of how to use urllib.request object from Python standard library.
import urllib.request
import json
from pprint import pprint
url = "https://app.close.com/hackwithus/3d63efa04a08a9e0/"
values = {
"first_name": "Vlad",
"last_name": "Bezden",
"urls": [
"https://twitter.com/VladBezden",
"https://github.com/vlad-bezden",
],
}
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
data = json.dumps(values).encode("utf-8")
pprint(data)
try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
pprint(res.decode())
except Exception as e:
pprint(e)
data
automatically creates a 'Content-Type', 'application/json; charset=utf-8' header, like in the other answer? –
Couscous You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4
code:
import urllib2,json
url = 'http://www.google.com/someservice'
postdata = {'key':'value'}
req = urllib2.Request(url)
req.add_header('Content-Type','application/json')
data = json.dumps(postdata)
response = urllib2.urlopen(req,data)
urllib2
has been removed in Python 3. Look for other examples using urllib
or requests
. –
Sharlenesharline In the lastest requests package, you can use json
parameter in requests.post()
method to send a json dict, and the Content-Type
in header will be set to application/json
. There is no need to specify header explicitly.
import requests
payload = {'key': 'value'}
requests.post(url, json=payload)
The Requests package used in many answers here is great but not necessary. You can perform a POST of JSON data succinctly with the Python 3 standard library in one step:
import json
from urllib import request
request.urlopen(request.Request(
'https://example.com/url',
headers={'Content-Type': 'application/json'},
data=json.dumps({
'pi': 3.14159
}).encode()
))
If you need to read the result, you can .read()
from the returned file-like object and use json.loads()
to decode a JSON response.
This one works fine for me with apis
import requests
data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)
data=data
parameter sends a form-encoded request, which is not JSON. Use json=data
instead. –
Sharlenesharline © 2022 - 2024 — McMap. All rights reserved.