Implementing API into Python program - python

I am using Requests to communicate with a simple api.
The code looks like this:
payload = {'text': reply, 'name': varname, 'avatar': varavatar}
r = requests.get('http://example.de/create.json', params=payload)
However, the result looks like this:
{"result": "error", "error": "error_no_direct_connection"}
This might be a problem with the api but I'm not sure.
So I printed out the URL that Requests created (print r.url).
It looks like this: http://url.com/create.json?text=Test&name=myname&avatar=http%3A%2F%2Fa0.url.com%2Fnormal.png
To make sure it's not a problem oft the api I tried it with curl. The command works!
curl --data-urlencode "text=Test" -d "name=myname" -d "avatar=http://url.com/normal.png" http://url.com/create.json

The curl option --data causes curl to submit a POST request, not a GET request. Try request.post(..., data=...).

Related

How can I get the data from an API using Python Request Post?

I'm trying to retrive some data from apptopia but I'm finding it pretty tricky (due to my lack of experience). In their authentication page: https://dev.apptopia.com/#authentication there are some instructions, but I just can't make it work.
I need a client and a secret (these bellow are not mine but the ones on the company's site)
client: JFqXPDhiLuvY
secret: L2nerprCksacBoFzUqtfHz8v
And I must use those information in order to obtain a Session token via HTTPS POST request:
curl -X "POST" "https://integrations.apptopia.com/api/login" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode "client=<client>" \
--data-urlencode "secret=<secret>"
I just don't know how to do it. I tried using the answen on this post: Python Request Post with param data but it didn't work. Could someone help me please? Thanks!
Did you try passing credentials as data in your request?
import requests
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
data = {
'client':your_client,
'secret':your_secret'
}
response = requests.post('https://integrations.apptopia.com/api/login', headers=headers, data=data)

Curl works but python requests doesn't

When I do curl, I get a response:
root#3d7044bac92f:/home/app/tmp# curl -H "Content-type: application/json" -X GET https://github.com/timeline.json -k
{"message":"Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}
However, when I do python requests to the same URL I get a status 410.
import requests
headers = {
'Content-type': 'application/json',
}
r = requests.get('https://github.com/timeline.json')
print r.json
root#3d7044bac92f:/home/app/tmp# python rest.py
<bound method Response.json of <Response [410]>>
What gives?
The host is a standard Ubuntu docker image and only installed Curl and some python modules. Python -V is 2.7
Note: I looked at this question but I can't telnet into above server so that solution doesn't apply to me:
Curl works but not Python requests
You've made at least two errors in your program.
1) You haven't specified the data= or headers parameters to the requests.get() call. Try this:
r = requests.get('https://github.com/timeline.json', data=data, headers=headers)
2) .json is a method, not a data attribute of the response object. As a method, it must be called in order to be effective. Try this:
print r.json()

How to translate curl command to urlfetch or request in general?

I'd like to issue an https request to an api from my gae-server, e.g. using urlfetch.
Example call is given as curl command.
curl <URL> \
-u <USER_KEY>: \
-d "infoa=123" \
-d "infob='ABC" \
-d "token=<SOME_TOKEN>" \
-d "description=Test"
All I want to know is, what the HTTPS request would look like, so I can replicate it using this documentation. Probably going about it wrong but I have used --trace-ascii - with curl but from the ouptut I still cannot 100% say what the request I am issuing looks like.
What aspect of an http-request do they translate to? Would it something like this work:
result = urlfetch.fetch(
url='<URL>',
payload={user: <USER_KEY>, data: {infoa=123, infob=ABC, ...}},
method=urlfetch.POST,
headers=headers)
So: -u for user goes into the authorization header. basic encryption is base64. -d for data goes into payload. Different -d are concatenated with a simple ampersand.
try:
headers = {'Content-Type': 'application/x-www-form-urlencoded',
"Authorization": "Basic %s" % base64.b64encode(<some_private_user_authentication>)} # base64 or similar needs to be imported
result = urlfetch.fetch(
url='<URL of endpoint>',
payload='infoa={}&infob={}&description=Test Transaction'.format(info_a, info_b),
method=urlfetch.POST,
headers=headers)
print repr(result.content) # do things..
except urlfetch.Error:
logging.exception('Caught exception fetching url')
print 'Caught exception fetching url' # do other things..

using testrail api in python script

I have the curl command, but not sure about how to run that in python script.
curl -H "Content-Type: application/json" -u "username:password" -d '{ "name":"something" }' "https://xxxxxxxx"
I'm planning to use subprocess, but the api documents aren't very helpful.
Also does anyone know how to get the sectionId from testrail?
Bill from TestRail here. You can find a link to our Python bindings here:
http://docs.gurock.com/testrail-api2/bindings-python
Regarding getting the section ID, you can use the get_sections method for a project/suite to return all the section details including IDs. You can find more info on that here:
http://docs.gurock.com/testrail-api2/reference-sections#get_sections
If you're looking for the section ID for a specific test case, you can get that from the get_case method.
You probably want to use the requests package for this. The curl command translates to something like this:
import json
import requests
response = requests.post('https://xxxxxxxx',
data=json.dumps({'name': 'something'}),
headers={'Content-Type': 'application/json'},
auth=('username', 'password'))
response_data = response.json()
If you really want to use subprocess, you can do something like this:
import subprocess
curl_args = ['curl', '-H', 'Content-Type: application/json', '-u', 'username:password',
'-d', '{ "name":"something" }', 'https://xxxxxxxx']
curl_output = subprocess.check_output(curl_args)
I consider the latter approach less "Pythonic".

compare python requests with curl

I am interfacing with an API using requests and requests_oauthlib.
I successfully authenticate and access all the GET methods of the API, but get error 500 with POST methods. For example:
r = oauth.post("https://api.timelyapp.com/1.0/1/clients",
data={"client":{"name":"newclient", "color":"c697c0" }},
allow_redirects=False, headers={"Content-Type": "application/json"})
The issue is that I tested the same exact call with curl and it works correctly, here the curl code:
curl -v -X POST -H "Content-Type: application/json" -H "Authorization: Bearer XXXXXXXXXXXX" --data '{"client": { "name": "newclient", "color":"c697c0" }}' "https://api.timelyapp.com/1.0/1/clients"
how can I dig deeper in requests to compare its call with curl?
UPDATE:
Also, noticed that if I do not specify content type:
r = oauth.post("https://api.timelyapp.com/1.0/1/clients",
data={"client":{"name":"newclient", "color":"c697c0" }},
allow_redirects=True)
I get instead a 302 with redirection to the site homepage, where I fetch the content of the page. In any case the new client is not added.
You might want to try this instead:
data=json.dumps(payload)
From python-requests doc:
There are many times that you 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.

Categories

Resources