I need to get access token to moving in the site with request
i do the same thigs that writen in the documentation:
{
"grant_type": "",
"client_id": "",
"client_secret": "",
"scope": "v2 read write"
}
My:
payload = {
"grant_type": "",
"client_id": f"{client_id}",
"client_secret": f"{client_secret}",
"scope": "read write v2"
}
headers = {
'accept': '*/*',
'accept-language': 'ru',
'content-type': 'application/json',
'user-agent': f'{fake_useragent}'
}
resp = requests.post(url=url,headers=headers,json=payload)
print(resp.json())
payload = {
"grant_type": "",
"client_id": f"{client_id}",
"client_secret": f"{client_secret}",
"scope": "read write v2"
}
headers = {
'accept': '*/*',
'accept-language': 'ru',
'content-type': 'application/json',
'user-agent': f'{fake_useragent}'
}
resp = requests.post(url=url,headers=headers,json=payload)
print(resp.json())
and than:
{'error': 'invalid_request', 'error_description': 'The grant type was not specified in the request', 'error_human_title': 'Некорректные данные.'}
As response client will receive:
{
"access_token": "454c3cd39a980500e9b787e03d53ec5c320f644b",
"expires_in": 86400,
"token_type": "bearer",
"scope": "v2 read write",
"refresh_token": "12a13560163da7901d7f74c89fc5df3ea7625942"
}
also tested on postman but got the same error, but in the develp. it's look like this enter image description here
What am i doing wrong?
postman
And also i tried that way
{
"grant_type": "authorization_code",
"client_id": "",
"client_secret": "",
"code": "",
"scope": "v2 read write",
"redirect_uri": "http://myadomain.com/auth/connect"
}
and than postman
Link to the documentation - https://developer.olx.ua/api/doc#section/Authentication/
Related
import requests
url = "xxxxy/v3/oauth2/token"
payload = {
"grant_type": "client_credentials",
"client_id": "xxxxx",
"client_secret": "xxxxx"
}
headers = {
"Accept": "application/json",
"Content-Type": "application/json"
}
response = requests.request("POST", url, json=payload, headers=headers)
print(response.text)
and my output is like this
Output: In output we can see access_token, token type and time to expire this key. I want output only the text that is in "access_token".
}
"tokenInfo": {
"access_token": "XFGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"expires_in": 3600,
"token_type": "Bearer"
}
}
How about the following?
# get json response and navigate to access token
json = response.json()
access_token = json["tokenInfo"]["access_token"]
print(access_token)
headers = {
"User-Agent": "Mozilla/5.0",
'accept': 'application/json',
'Content-Type': 'application/json',
}
with open("jsonattempt.txt","r") as f:
data = f.read()
json_data = "'" + data + "'"
response = requests.post('https://www.pathofexile.com/api/trade/search/Standard', headers=headers, data=json_data)
print(response)
Generally, there is a curl request like this:
curl -X 'POST' \
'https://www.pathofexile.com/api/trade/search/Standard' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"query": {
"status": {
"option": "online"
},
"type": "Turquoise Amulet",
"stats": [
{
"type": "and",
"filters": [
{
"id": "pseudo.pseudo_total_mana",
"value": {
"min": 47,
"max": 49
},
"disabled": false
}
]
}
]
},
"sort": {
"price": "asc"
}
}'
Which returns a bunch of unnecessary things.
My json_data variable and jsonattempt.txt is the same as -d parameter, I add ' ' to start and to end:
{
"query": {
"status": {
"option": "online"
},
"type": "Turquoise Amulet",
"stats": [
{
"type": "and",
"filters": [
{
"id": "pseudo.pseudo_total_mana",
"value": {
"min": 47,
"max": 49
},
"disabled": false
}
]
}
]
},
"sort": {
"price": "asc"
}
}
I convert curl request to python which is the code on the top, I add the data as json_data and yeet the post request but keep getting 400 Bad Request.
Request 401 is Unauthorized AFAIK, so I dont need an OAuth2 key for this. How can I insert my json file appropiately to the request?
(Same exact json works on https://app.swaggerhub.com/apis-docs/Chuanhsing/poe/1.0.0#/Trade/get_api_trade_fetch__items_ I am just asking how to insert my json file to requests.post correctly.)
Why are you adding quotes around the JSON content? That doesn't make any sense. Those quotes aren't part of your curl request. If you just write...
import requests
headers = {
"User-Agent": "Mozilla/5.0",
"accept": "application/json",
"Content-Type": "application/json",
}
with open("jsonattempt.txt", "r") as f:
data = f.read()
response = requests.post(
"https://www.pathofexile.com/api/trade/search/Standard",
headers=headers,
data=data,
)
print(response)
...it works as expected.
And in fact you can further simplify that; you don't need to read in the file data yourself, you can let requests do that:
import requests
headers = {
"User-Agent": "Mozilla/5.0",
"accept": "application/json",
"Content-Type": "application/json",
}
with open("jsonattempt.txt", "r") as f:
response = requests.post(
"https://www.pathofexile.com/api/trade/search/Standard",
headers=headers,
data=f,
)
print(response)
import json
# some codes here
with open("jsonattempt.txt","r") as f:
data = f.read()
json_data = json.loads(data)
# rest of codes here
Your request requires json type data, while you are passing a string. The json.loads method converts string to json. Try it out.
I'm trying to translate Curl to Python, but I'm getting something wrong. Please help.
CURL:
body=$(cat << EOF
{
"order": {
"units": "-100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)
curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
-d "$body" \
"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"
PYTHON:
import requests
import json
def market_buy():
header = {"Accept": "application/json",
"Authorization": "Bearer <my auth code>"
}
data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
url = "https://api-fxtrade.oanda.com/v3/accounts/<myaccount>/orders"
r = requests.post(url, data=data, headers=header)
print(r.text)
market_buy()
Error Message:
{"errorMessage":"Insufficient authorization to perform request."}
I've double-checked my credentials. I'm thinking something is wrong with the code.
A direct translation from cURL to Python requests would be this:
from requests import post
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer <AUTHENTICATION TOKEN>",
}
data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT",
}
}
post(
"https://api-fxtrade.oanda.com/v3/accounts/<myaccount>/orders",
headers=headers,
data=data,
)
I guess you are missing the SSL cert verification and basic authentication.
You can turn off SSL cert verification with the verify flag, and use basic authentication by specifying auth.
from requests.auth import HTTPBasicAuth
import requests
import json
def market_buy():
header = {"Accept": "application/json",
"Authorization": "Bearer <my auth code>"
}
data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
url = "https://api-fxtrade.oanda.com/v3/accounts/<myaccount>/orders"
r = requests.post(url, data=data, headers=header, auth=HTTPBasicAuth('admin', 'admin'), verify=False)
print(r.text)
market_buy()
I guess the above should work.
I can run this curl statemtent with curl and works perfectly. I have read many post but nothing works.
curl -X POST "http://some.website.com" -H "accept: application/json" -H "authorization: Basic authcode" -H "Content-Type: application/json" -d "{ \"Fields\": [ \"string\" ], \"Filters\": [ { \"Field\": \"Item\", \"Operator\": \"=\", \"Value\": \"119001\" } ], \"PageSize\": 0, \"PageNumber\": 0}"
code tried so far
import requests
session = requests.Session()
url = 'http://some.website.com'
headers = {'accept': 'application/json', 'authorization': 'Basic authcode', 'Content-Type': 'application/json'}
data = {'Fields': 'string', 'Filters': { 'Field': 'Item', 'Operator': '=', 'Value': '119001' }, 'PageSize': 0, 'PageNumber': 0}
response = session.post(url, headers=headers, data=data)
print(response.status_code)
print(response.json())
Error = not valid JSON Value
I have also tried
import simplejson as json
# ...
# ...
response = session.post(url, headers=headers, data=json.dumps(data))
# ...
# ...
Failed = Error detecting JSON fields
I think it has something to do with the nested dict statement
Using https://httpbin.org/post I can see what data (headers and body) are received on server and I see the same result for curl
curl -X POST "http://httpbin.org/post" -H "accept: application/json" -H "authorization: Basic authcode" -H "Content-Type: application/json" -d "{\"Fields\": [\"string\"], \"Filters\": [{\"Field\": \"Item\", \"Operator\": \"=\", \"Value\": \"119001\"}], \"PageSize\": 0, \"PageNumber\": 0}"
# result
{
"args": {},
"data": "{\"Fields\": [\"string\"], \"Filters\": [{\"Field\": \"Item\", \"Operator\": \"=\", \"Value\": \"119001\"}], \"PageSize\": 0, \"PageNumber\": 0}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json",
"Authorization": "Basic authcode",
"Content-Length": "122",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/7.58.0"
},
"json": {
"Fields": [
"string"
],
"Filters": [
{
"Field": "Item",
"Operator": "=",
"Value": "119001"
}
],
"PageNumber": 0,
"PageSize": 0
},
"origin": "83.23.32.69, 83.23.32.69",
"url": "https://httpbin.org/post"
}
and Python (using json=data or data=json.dumps(data) instead of data=data)
import requests
headers = {
'Accept': 'application/json',
'Authorization': 'Basic authcode',
# 'Content-Type': 'application/json',
# 'User-Agent': 'Mozilla/5.0',
}
data = {
"Fields": [ "string" ],
"Filters": [ { "Field": "Item", "Operator": "=", "Value": "119001" } ],
"PageSize": 0,
"PageNumber": 0
}
response = requests.post('https://httpbin.org/post', headers=headers, json=data)
print(response.text)
# result
{
"args": {},
"data": "{\"Fields\": [\"string\"], \"Filters\": [{\"Field\": \"Item\", \"Operator\": \"=\", \"Value\": \"119001\"}], \"PageSize\": 0, \"PageNumber\": 0}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Basic authcode",
"Content-Length": "122",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0"
},
"json": {
"Fields": [
"string"
],
"Filters": [
{
"Field": "Item",
"Operator": "=",
"Value": "119001"
}
],
"PageNumber": 0,
"PageSize": 0
},
"origin": "83.23.32.69, 83.23.32.69",
"url": "https://httpbin.org/post"
}
There are only differences in headers: "User-Agent": "curl/7.58.0" and "User-Agent": "python-requests/2.22.0". And Python uses "Accept-Encoding": "gzip, deflate".
BTW: you can use portal curl.trillworks.com to convert curl to Python code
I am working on REST API of a site that requires this request type when I want to upload a file:
'Authorization' and multi-part content type in header
File as binary string in form (body)
File Type in request URL
So I did this code:
import requests
url = 'http://httpbin.org/post'
parameters = {
'format': 'pdf',
}
headers = {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json',
'Authorization' : 'Some authorization code'
}
data = {'file': open('1.pdf', 'rb')}
r = requests.post(url, params=parameters, headers=headers, data=data)
print(r.text)
BUT it seems to requests is dropping data :
{
"args": {
"format": "pdf"
},
"data": "",
"files": {},
"form": {},
"headers": {
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Some authorization code",
"Connection": "close",
"Content-Length": "30",
"Content-Type": "multipart/form-data",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.1"
},
"json": null,
"origin": "x.x.x.x",
"url": "http://httpbin.org/post?format=pdf"
}
it works when I remove 'headers' part in request:
r = requests.post(url, params=parameters, data=data)
Because response is :
{
"args": {
"format": "pdf"
},
"data": "",
"files": {},
"form": {
"fax_file": "some samplae texts\n"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "30",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.1"
},
"json": null,
"origin": "x.x.x.x",
"url": "http://httpbin.org/post?format=pdf"
}
I have tried prepared request too and result is same.
You are trying to post file data, so use the files option:
r = requests.post(url, params=parameters, files=data, headers=headers)
You should really not set the Content-Type header, however; it is set for you when you use the files option. The header in this case includes the field boundary, to really want the library to take care of this for you:
headers = {
'Accept': 'application/json',
'Authorization' : 'Some authorization code'
}
If you leave the Content-Type header in, you’d have to generate the content body up front to be able to supply the required boundary info to the receiving server.
You could experiment with dropping the Accept header too; by default requests will add Accept: */* if you don't specify that header, signalling that anything is acceptable.
When using only the data argument, the parameters are encoding to application/x-www-form-urlencoded form, which doesn't support large file data, and your Content-Type header doesn't match the actual POST body content.
See Post a Multipart-Encoded File in the requests documentation and application/x-www-form-urlencoded or multipart/form-data? here on Stack Overflow.
Demo:
>>> import requests
>>> url = 'http://httpbin.org/post'
>>> parameters = {'format': 'pdf'}
>>> headers = {
... 'Accept': 'application/json',
... 'Authorization' : 'Some authorization code',
... }
>>> data = {'file': open('1.pdf', 'rb')}
>>> r = requests.post(url, params=parameters, files=data, headers=headers)
>>> print(r.text)
{
"args": {
"format": "pdf"
},
"data": "",
"files": {
"file": "<file data as base64>"
},
"form": {},
"headers": {
"Accept": "application/json",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Some authorization code",
"Cache-Control": "max-age=0",
"Connection": "close",
"Content-Length": "374751",
"Content-Type": "multipart/form-data; boundary=d4b84f8bfd464e3f97e3de584d7315fc",
"Host": "httpbin.org",
"O2Gw-Id": "03",
"User-Agent": "python-requests/2.18.4",
"X-Gateway": "wap.london.02.net"
},
"json": null,
"origin": "10.120.6.78, 82.132.221.209",
"url": "http://httpbin.org/post?format=pdf"
}
Note the multipart/form-data; boundary=d4b84f8bfd464e3f97e3de584d7315fc value for the Content-Type header!