Can't get a response in JSON format, python - python

I am trying to execute a get request to a service that can send responses in JSON or xml. In the header, I specify Content-Type 'application/json', but I get a response in xml format. I performed the same query using SOAP UI and received a JSON response.
Maybe something is wrong in my request?
import requests
myheader = {'Content-Type': 'application/json'}
auth = requests.get ("""myurl/authenticate""", auth=('user','password'),
headers = myheader)
url = 'myurl/service'
req = requests.get(url = url,
header = myheader,
cookies=auth.cookies)
print(req.json)
print(req.text)
Error text on 'print(req.json)':
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Problem solved by fixing header:
myheader={'Content-type': 'application/json', 'Accept': 'application/json'}

Related

How to get json text by request with header details?

I would like to go to page https://losoviny.iamroot.eu/part_one and write json text from there.
End at first I must login in https://losoviny.iamroot.eu/part_one_login and use
details in header.
But if If I run code I see:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Do you know how to rewrite it?
(Header data are correct)
Thank you
import json
import requests
headers = {
'username': 'Loskarlos',
'password': 'JednohoDneOvladnuKSI'
}
response = requests.post('https://losoviny.iamroot.eu/part_one_login', headers=headers)
response_get = requests.get('https://losoviny.iamroot.eu/part_one ')
response_get = json.loads(response_get.json())
print(response_get)
First you need to get the token from https://losoviny.iamroot.eu/part_one_login in order to test the API use postman. Your initial response is not a header element. It is a form, use below code to get the token.
import requests
url = "https://losoviny.iamroot.eu/part_one_login"
payload={'username': '<User NAME>',
'password': '<Password>'}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
After this I have no idea to pass the token header as per below code. Use header parameters when consuming the part_one endpoint. For header use Bearer format to build the Authorization header parameter.
import requests
url = "https://losoviny.iamroot.eu/part_one"
payload={}
headers = {
'Authorization': 'Bearer <TOKEN>'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
As a practice use postman like tool to navigate an API. cheers!!!
import requests
url = "https://losoviny.iamroot.eu/part_one_login"
payload={'username': 'Loskarlos',
'password': 'JednohoDneOvladnuKSI'}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

REST API post request results in successful request but not creation

I've been trying to make a Post Request to my CRM API. The CRM API is very vague:
"You can use POST request when you wish to create records. You POST a JSON encoded string to the servers and it will return a single instance of the record."
POST /{object_name}
Example:
Request URL (POST):
/accounts
Request Body (JSON):
{
"name": "testing API"
}
I've had plenty of success making GET requests regularly, but POST is not working out so easily.
url = "https://apiv4.reallysimplesystems.com/accounts?<KEY>"
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
headers = {
'Content-Type': 'application/json',
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
}
response = requests.post(url, headers=headers, data=payload)
I get a status code 200 when I run this, but I'm really looking for that 201. The only clue that I've got to follow at this point is that when I run:
response.json()
I get the error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I've tried switching the response parameters to json:
response = requests.post(url, headers=headers, json=payload)
I've tried ensuring that my payload is json by using json.dumps():
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
payload = json.dumps(payload)
And I've tried all sorts of other shenanigans that I can't even recall at this point. Does anyone have any idea where I'm going wrong here? The 200 status code makes me feel painfully close.
Replace <AUTH_TOKEN> with your auth token
url = "https://apiv4.reallysimplesystems.com/accounts/"
payload = {"name":"Ziggy"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH_TOKEN>',
}
response = requests.post(url, headers=headers, data=payload)
Problem solved:
import json
import requests
url = "https://apiv4.reallysimplesystems.com/accounts"
payload = {"name":"RSS Test Joe Bloggs","addresscounty/state":"Maryland","source":"Word of Mouth"}
payload = json.dumps(payload)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH KEY>'
}
response = requests.post(url, headers=headers, data=payload)
Rather than using Postman's code which included the in the URL and used :
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
I replaced it with a standard Authorization header. Secondly, I found that using json.dumps(payload) and json = payload was resulting in a Bad Request.

How to generate json response from python?

I am making an API call from Python. My current code is supposed to generate a JSON response, but throws out a Response code 500 (Internal Server Error). However, when I generate the data using the API's built in extract tool, it returns the data. Code snippet is as follows:
def Performance(data):
BASEURL = 'https://api-c31.ict.com/inContactAPI/'
accessToken = (data["access_token"])
#Check if accessToken is empty or null
if accessToken!= "":
#Give necessary parameters for http request
payload={'startDate':'1/1/2020',
'endDate':'1/6/2020',
'fields':'"agentId","teamId","totalHandled"'}
#add all necessary headers
header_param = { 'User-Agent' : 'Chrome/79.0.3945.117',
'Authorization': 'bearer ' + '{accessToken}',
'content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/javascript, */*'
}
# Make get http request
response_1 = requests.get(BASEURL + 'services/{version}/agents/performance' , headers = header_param, params=payload)
#answer1.raise_for_status
#print response appropriately
print (response_1)
#response
else: print('error')
response_1 generates a Response 500. How can I generate the data from Python?
params doesn't encode your payload as JSON; json does.
response_1 = requests.get(
BASEURL + 'services/{version}/agents/performance',
headers=header_param,
json=payload)

Python Requests Code 141 Error

I'm trying to use requests in python to post a json dictionary to a url. I need to get a string back from the url but I keep getting a code 141 error -{"code":141,"error":"Missing a github repository link"}. I'm using this website(http://docs.python-requests.org/en/latest/user/quickstart/) to do requests.
Any ideas on why I keep getting that error? Code is below.
import requests
import json
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", params = payload, headers = headers)
print(r.url)
print r.text
Update: The suggestion worked but now I'm getting an{"code":141,"error":"success/error was not called"} error when I try to save the response I recieve from the url into a variable and then post it back to a different url.
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
Since you are making a POST request and you need to provide a JSON in the request body, use json argument, not params:
r = requests.post("http://challenge.code2040.org/api/register",
json=payload,
headers=headers)
(tested - got back a token)
Note that json argument was introduced in requests 2.4.2.

Sending POST request to a webservice from python

I'm trying to send a POST request to a restful webservice. I need to pass some json in the request.It works with the curl command below
curl --basic -i --data '<json data string here>' -H Content-type:"text/plain" -X POST http://www.test.com/api
I need some help in making the above request from Python. To send this POST request from python I have the following code so far:
import urllib
url='http://www.test.com/api'
params = urllib.urlencode... #What should be here ?
data = urllib.urlopen(url, params).read()
I have the following three questions:
Is this the correct way to send the resuest ?.
How should i specify the params value ?
Does content-type need to be specified ?
Please Help
Thank You
The documentation for httplib has an example of sending a post request.
>>> import httplib, urllib
>>> params = urllib.urlencode({'#number': 12524, '#type': 'issue', '#action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
302 Found
>>> data = response.read()
>>> data
'Redirecting to http://bugs.python.org/issue12524'
>>> conn.close()
Construct a dict of the data you want to be sent as a POST request.
urlencode the dict to get a string.
urlopen the URL you want, passing in the optional data parameter as your encoded POST data.
the question deals with sending the parameters as "json"..
you need to set the Content-Type to application/json in the headers and then send the paramters without urlencoding..
ex:
url = "someUrl"
data = { "data":"ur data"}
header = {"Content-Type":"application/json","User-Agent":"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"}
#lets use httplib2
import httplib2
http = httplib2.Http()
response, send = http.request(url,"POST",headers=header,body=data)
You don't need urllib.urlencode() if Content-Type is not application/x-www-form-urlencoded:
import json, urllib2
data = {"some": "json", "d": ["a", "ta"]}
req = urllib2.Request("http://www.test.com/api", data=json.dumps(data),
headers={"Content-Type": "application/json"})
print urllib2.urlopen(req).read()
import requests
endpoint = 'https://xxxxxxxxxxxxxxxxxxx.com'
headers = {'Content-Type': 'text/plain'}
data = '{ id: 1 }'
result = requests.post(endpoint, headers=headers, data=data)
print(result)
Here's a sample snippet on POST request of json. The results will be printed in your terminal.
import urllib, urllib2
url = 'http://www.test.com/api'
values = dict(data=json.dumps({"jsonkey2": "jsonvalue2", "jsonkey2": "jsonvalue2"}))
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
rsp = urllib2.urlopen(req)
content = rsp.read()
print content

Categories

Resources