I have sent a JSON request. I am getting a 200 response which means that the sent request was accepted and that there is a response. I am trying to view the full response that was sent back from the request. I have tried 3-4 different ways of viewing the response, but no matter what i try, i cant figure out how to view the full response... Can anyone help me figure out how to see the information..
Request -
def createUserSynapse():
url = 'http://uat-api.synapsefi.com'
headers = {
'X-SP-GATEWAY' : 'client_id_asdfeavea561va9685e1gre5ara|client_secret_4651av5sa1edgvawegv1a6we1v5a6s51gv',
'X-SP-USER-IP' : '127.0.0.1',
'X-SP-USER' : 'ge85a41v8e16v1a618gea164g65',
'Contant-Type' : 'application/json',
}
payload = {
"logins":[
{
"email":"test#test.com",
}
],
"phone_numbers":[
"123.456.7890",
"test#test.com",
],
"legal_names":[
"Test name",
],
"extras":{
"supp_id":"asdfe515641e56wg",
"cip_tag":12,
"is_business":False,
}
}
print(url)
print(headers)
print(payload)
call = requests.post(url, data=json.dumps(payload), headers=headers)
print(call)
return call
The response that i am getting from the request (I have a line to print the request)...
<Response [200]>
Try changing call to
call.text
For JSON try
json.loads(call.text)
To print
print(json.loads(call.text))
Related
This is my first project using API/python. Basically, I want to get information from trackhive.com to see where is the package. But first, to understand how it works, I'm just trying to create a track.
On the website, they give me this example:
from urllib2 import Request, urlopen
values = """
{
"tracking_number": "9361289676090919095393",
"slug": "usps"
}
"""
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer Token'
}
request = Request('https://private-anon-6175dd5596-trackhive.apiary-proxy.com/trackings
', data=values, headers=headers)
response_body = urlopen(request).read()
As I'm using Python 3, my code is
import json
import urllib.request
values = """
{
"tracking_number": "9361289676090919095393",
"slug": "usps"
}
"""
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer mytokenAPI'
}
url = 'https://private-anon-6175dd5596-trackhive.apiary-proxy.com/trackings'
request = urllib.request.Request(url,data=values, headers=headers)
response_body = urllib.request.urlopen(request, data=bytes(json.dumps(headers), encoding="utf-8")).read()
But when it calls the "urllib.request.urlopen", it returns "HTTPError: Bad Request". What am I doing wrong?
On the website, they said that the endpoint is located at: https://api.trackinghive.com. In their code, they are accessing: 'https://private-anon-6175dd5596-trackhive.apiary-proxy.com/trackings'. If I haven't access to their example, how could I know that I suppose to access this URL, and not something like "https://api.trackinghive.com/trackings"? Isn't it suppose to use the endpoint somewhere?
(I'm sorry about all these questions, I'm a little confused about how these codes with API and URL works)
I appreciate any help ^^
Edit:
Link to documentation:
https://trackhive.docs.apiary.io/#introduction/api-requirements/end-point
If I register on https://my.trackinghive.com/login and generate API key then code works for me.
I use requests instead of urllib because it is easier to create POST request. And documentation shows that it has to be POST, not GET.
And it is easier to send JSON data. It doesn't need header Content-Type': 'application/json' because requests will add it automatically when is use json=.... And it doesn't need to convert values to one string because requests will do it automatically.
BTW: I don't need module json to work with data. I use it only to convert it to string with indentation to display it.
import requests
values = {
"tracking_number": "9361289676090919095393",
"slug": "usps"
}
token = 'eyJh....'
headers = {
'Authorization': f'Bearer {token}' # both works for me
#'Authorization': f'{token}'
}
url = 'https://api.trackinghive.com/trackings'
r = requests.post(url, headers=headers, json=values)
print('\n--- as text ---\n')
print(r.text)
print()
print('\n--- as dict/list ---\n')
data = r.json()
print('keys:', list(data.keys()))
print('message:', data["meta"]["message"][0])
# - show it more readable -
print('\n--- more readable ---\n')
import json
text = json.dumps(data, indent=2)
print(text)
Result:
--- as text ---
{"meta":{"code":409,"message":["Tracking already exists."]},"data":{"_id":"60a5b5a0aa4e400011a0c657","current_status":"Pending","return_to_sender":false}}
--- as dict/list ---
keys: ['meta', 'data']
messge: Tracking already exists.
--- more readable ---
{
"meta": {
"code": 409,
"message": [
"Tracking already exists."
]
},
"data": {
"_id": "60a5b5a0aa4e400011a0c657",
"current_status": "Pending",
"return_to_sender": false
}
}
First time trying to extract data via an API. I'm getting stuck with how to pass the raw data. I have been able to get it to work in postman but I can't quite figure it out with Python.
I've been getting this error:
{'fault': {'faultstring': 'JSONThreatProtection[JSON-Threat-Protection-1]: Execution failed. reason: Expecting { or [ at line 1', 'detail': {'errorcode': 'steps.jsonthreatprotection.ExecutionFailed'}}}
I'm pretty sure its the data portion that is wrong but I haven't been able to figure out if it's just a syntax error or something bigger that I'm missing.
My code as follows:
import requests
import json
url = "https://url/customers/shipmentstatus"
headers = {
"Authorization": "Bearer TOKEN",
"Content-Type": "application/json"
}
data = {
"Id": [
"AZ1234"
]
}
response = requests.post(url, headers=headers, data=data)
print(response.json())
Your code posts the data as form encoded data, not as JSON. That's because you use the data parameter to supply the payload. To fix, encode the data as JSON using json.dumps():
response = requests.post(url, headers=headers, data=json.dumps(data))
But a better way is to pass the data to requests using the json parameter:
response = requests.post(url, headers=headers, json=data)
Using the json parameter is easier and it will also add the Content-Type: application/json header for you.
I am trying to pull a list of conversations from Intercom using their API, restricted based on the date that they were updated.
Their site (https://developers.intercom.com/intercom-api-reference/reference#search-for-conversations) says
To search for conversations, you need to send a POST request to
https://api.intercom.io/conversations/search. This will accept a query
object in the body which will define your filters in order to search
for conversations.
So I tried:
import requests
url = 'https://api.intercom.io/conversations/search'
data_params = {
"query": {
"field": "updated_at",
"operator": ">",
"value": 1560436784
}
}
headers = {'Authorization' : 'Bearer ******************', 'Accept':'application/json', 'Content-Type':'application/json'}
r = requests.post(url, headers = headers, data = data_params)
r.status_code
This consistently runs into a 400 'Bad Request' error, but I'm struggling to see why. I've also tried json = data_params in the post call but same result. I appreciate the code might not be fully reproducible as it requires an authenticated API connection, but if there's anything obviously wrong it would be good to know!
Obviously, there seems no obviously error here.
for the 400 Bad Request . I think you should do the check of you data_params if there's something missing or in bad format. also the headers
You should try converting the data_params dictionary to json.
I tested with json.dumps and this seems to have worked:
import json
url = 'https://api.intercom.io/conversations/search'
data_params = {
"query": {
"field": "updated_at",
"operator": ">",
"value": 1560436784
}
}
headers = {'Authorization' : 'Bearer ******************', 'Accept':'application/json', 'Content-Type':'application/json'}
r = requests.post(url, headers = headers, data = json.dumps(data_params))
print(r.status_code)
Hi i'm trying to add a user to my guild using Discord's API.
The Scope I'm using is Guild.Join, Identify and Guilds. identify%20guilds%20guilds.join
The URL Is https://discordapp.com/api.
Here's my code:
#staticmethod
def add_to_guild(access_token, userID):
url = f"https://discordapp.com/api/guilds/{guildId that I cant show}/members/{userID}"
botToken = "<Bot Token I can't SHow haha>"
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
payload = {
'access_token' : access_token
}
response = requests.put(url=url, data=payload, headers=headers)
print(response.text)
when I call this method, I receive this error:
{"message": "400: Bad Request", "code": 0}
I've been through the Discord's Documentation countless of times and searched the internet to no avail.
Can someone please help ? Thanks.
you had to replace data to json
def add_to_guild(access_token, userID):
print(userID)
url = f"{Oauth.discord_api_url}/guilds/<GuildID>/members/{userID}"
headers = {
"Authorization" : "Bot <bottoken>",
"Content-Type": "application/json"
}
payload = {
'access_token' : str(access_token)
}
response = requests.put(url=url, json=payload, headers=headers)
print(response.text)
The userID is enough I am not sure why you want the payload or access token; Try to drop the payload part.
If you are trying to add a user, the user has to agree to grant you some permissions check here https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes so the token I think will be the "Bearer" tokens. Check the doc I've shared.
I am trying to insert a destination order using action=insertDestinationOrder
I am using POST method with all required parameters, but keep getting
{
"errorCode": 40,
"errorMsg": "general error"
}
I have checked using postman too. But still same.
Below is the request using python requests package.
import requests
url = "https://csv.telematics.tomtom.com/extern"
payload = "orderid=TO0049&country=DE&city=Cologne&latitude=50974519&ordertype=delivery%20order&zip=50735&longitude=6977319&street=Am%20Niehler%20Hafen%20%26%20Stapelkai%2C%2050735%20Cologne%20(Niehl)&account=XXXX&username=XXXX&password=XXXX&apikey=XXXX&lang=en&action=insertDestinationOrder&ordertext=Am%20Niehler%20Hafen%20%26%20Stapelkai%2C%2050735%20Cologne%20(Niehl)&useUTF8=true&outputformat=json"
headers = {
'content-type': "application/x-www-form-urlencoded"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
Need some help.
Try adding a ? to the end of the url, or to the start of the payload:
url = "https://csv.telematics.tomtom.com/extern?"
or
payload = "?orderid=TO0049&country=DE&city=Cologne&latitude=50974519&ordertype=delivery%20order&zip=50735&longitude=6977319&street=Am%20Niehler%20Hafen%20%26%20Stapelkai%2C%2050735%20Cologne%20(Niehl)&account=XXXX&username=XXXX&password=XXXX&apikey=XXXX&lang=en&action=insertDestinationOrder&ordertext=Am%20Niehler%20Hafen%20%26%20Stapelkai%2C%2050735%20Cologne%20(Niehl)&useUTF8=true&outputformat=json"