cURL, API in Python - python

I'm trying to code the following cURL API request in Python:
curl -X POST 'https://api.livecoinwatch.com/coins/list' \
-H 'content-type: application/json' \
-H 'x-api-key: <YOUR_API_KEY>' \
-d '{"currency":"USD","sort":"rank","order":"ascending","offset":0,"limit":2,"meta":false}'
I tried solving it with guidance of another post, like this:
headers = {
'x-api-key': <YOUR_API_KEY>,
'content-type': 'application/json',
'host': https://api.livecoinwatch.com/coins/list
}
url = https://api.livecoinwatch.com/coins/list
data = '{"currency": "USD","sort": "rank","order": "ascending","offset": 0,"limit": 50,"meta": true}'
response = requests.post(url, data=json.dumps(data), headers=headers)
print (response)
Unfortunately I get a "bad request" error.
Can someone please help me where I go wrong?

Assuming you have your urls wrapped in quotes, you should try giving to the data function parameter a dictionary instead of a string as the requests documentation says: data – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the Request.
response = requests.post(url, data=json.loads(data), headers=headers)

Related

How to curl in Python with header, data?

I'm trying replace the following curl command by a Python script:
curl --request POST \
--url https://xx.com/login \
--header 'Content-Type: application/json' \
--data '{
"email": "user#domain.com",
"password": "PASSWORD"
}'
Script that I tried:
import urllib.request
import json
body = {"email": "xxx#xx.com","password": "xxx"}
myurl = "https://xx.com/login"
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)
When I tried to run this script, it doesn't return me anything and show processed completed. Is my code logic correct? Or there is something wrong with my code?
For HTTP and HTTPS URLs, urllib.request.urlopen function returns a http.client.HTTPResponse object. It has different attributes and methods you can use,
For example,
HTTPResponse.read([amt]) - Reads and returns the response body, or up to the next amt bytes.
HTTPResponse.getheaders() - Return a list of (header, value) tuples.
HTTPResponse.status - Status code returned by server.
So in your case you could do check the status using status attribute . If it's successful read the response body using read method.
status_code = response.status
if status_code == 200: # request succeeded
response_body = response.read() # This will be byte object
response_body_as_string = response_body.decode('utf-8')
you can simply just use requests:
import requests
headers = {
'Content-Type': 'application/json',
}
data = '{\n"email": "user#domain.com",\n"password": "PASSWORD"\n}'
response = requests.post('https://xx.com/login', headers=headers, data=data)

GET Request from API via Python export to csv

I'm trying to write a api script via python. I want to access the URL "https://xxx/2.0/article" via "requests.get" so that it is displayed. If this was successful, I want to reprogram it to write all "articles" into a CSV.
I worked with curl first and it worked well
curl -X GET \
https://xxx/2.0/contact \
-H 'Accept: application/json' \
-H 'Authorization: Bearer {access-token}'
It also displayed the data directly. When I tried this with Python, it gave me an "Unauthorized".
import requests
newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.get('https://api.bexio.com/2.0/article', headers={'Authorization': 'newHeaders'
'Bearer '})
print(response.status_code)
print(response.text)
I don't know exactly what I have to do to make this work and how I can export/write this directly to a CSV.
Can anyone help me here?
Thanks!
I fixed it with the auth
#!/usr/bin/python
import requests
url = "https://api.bexio.com/2.0/article"
headers = {
'Accept': "application/json",
'Content-Type': "application/json",
'Authorization': "Bearer }
response = requests.request("GET", url, headers=headers)
print(response.text)
I saw my fault. The last question is, how can i get the output in a csv file? When I make an export of my stock in the frontend, I get a CSV with the fields "Product" "Code" "Storage location" Purchase value" "Stock" and "Minimum stock". But with the script comes of course much more output.

Trouble converting curl commands to python requests

I'm trying to grab some data from a website using API, but I'm having trouble converting the example curl command to python requests.
example curl command
curl -X POST "some_url" \
-H "accept: application/json" \
-H "Authorization: <accesstoken>" \
-d #- <<BODY
{}
BODY
My python requests that didn't work
headers = {
'Authorization': "Bearer {0}".format(access_token)
}
response = requests.request('GET', "some_url",
headers=headers, allow_redirects=False)
I get error code 400, can anyone help me figure out what was wrong?
The equivalent requests code for your curl should be:
import requests
headers = {
'accept': 'application/json',
'Authorization': '<accesstoken>',
}
data = "{} "
response = requests.post('http://some_url', headers=headers, data=data)
You can use https://curl.trillworks.com/ to convert your actual curl invocation (note that it won't handle heredocs, as in your example).
If you see different behavior between curl and your python code, dump the HTTP requests and compare:
Python requests - print entire http request (raw)?
How can I see the request headers made by curl when sending a request to the server?

Transforming CURL request to Python using requests library

Have a CURL request like that:
curl -X POST "https://page.com/login"
-H "accept: application/json" -H "Content-Type: application/json"
-d "{ \"username\": \"admin\", \"password\": \"pass\"}"
In Python I guess it should look like this:
import requests
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
data = {'username': 'admin', 'password': 'pass'}
response = requests.post('https://page.com/login', headers=headers, data=data)
response
After this it gives me [502] error for bad gateway. What am I doing wrong with my python query and how it should be modified?
Try using:
requests.post(..., json=data)
When you use data= requests will send it form encoded, to actually put json in the body you have to use json=

Calling Curl API on Python

I want to call CURL API on python.
curl -X POST -H "Authorization:Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5" \
-H "Content-Type: application/json" \
-d '{"module_id":"[MODULE_ID]", "text": "example text"}' \
-D - \
https://api.tocall.com/
I used requests module for making request and json module for converting object to string. But I'm getting 404.
Where am I wrong?
import requests
import json
headers = {
'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
'Content-Type': 'application/json',
}
url = "https://api.tocall.com/"
data = '{"module_id":"[MODULE_ID]", "text": "example text"}'
response= requests.post(url, data=json.dumps(data), headers=headers)
print(response.status_code)
You are encoding your data as JSON twice. json.dumps() takes an object and converts to JSON. In this case, you are converting a string to JSON. This should work better:
import requests
headers = {
'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
}
url = "https://api.tocall.com/"
data = {"module_id":"[MODULE_ID]", "text": "example text"}
response= requests.post(url, json=data, headers=headers)
print(response.status_code)
If it still doesn't work and you need more help, you should include real details about your API so we can reproduce the issue.
json.dumps turns a Python dict to a string, but your data is already a string. The easiest thing to do is write data as a dict then use json.dumps on that.
Add the Host header, so that the final server knows on which virtual host to route the request,
Change:
headers = {
'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
'Content-Type': 'application/json',
}
For:
headers = {
'Authorization': 'Token 00d2e3a10c82420414b2d36d28fb5afc2cd8e8a5',
'Content-Type': 'application/json',
'Host' : 'api.tocall.com'
}
I think this will fix your issue. Eventually you might want to update the default headers, not craft your own ones. Try to use the session features of requests to perform consistent queries.
Note: as stated by other answers, you have other JSON encoding issues, but that's not the reason why you are getting 404.

Categories