Getting Converting Value Error While Sending Data With Python Requests Module - python

Hello I'm trying to send a data with python requests module. I'm getting that "Converting Value Error" when I execute it. I don't know what is this error means. Thanks for any help.
Here is my error:
{'statusCode': 200, 'statusMessage': 'OK', 'result': None, 'errors': [{'field': '', 'message': 'Error converting value "{"price": 64, "stock": 11, "expiration": "2021-08-18 17:41:50.956382+00:00", "product": {"name": "Cerave Hydrating Cleanser Nemlendircili Temizleyici 236 ml", "barcode": "3337875597180"}}" to type \'System.Collections.Generic.List`1[DataTransferObjects.Listings.CreateOutSourcedListingModel]\'. Path \'\', line 1, position 207.'}]}
My code is here:
token = self.get_token()
create_listing_path = "api/v1/listings/createlistings"
create_listing_url = "https://staging.lab.xxx.com/" + create_listing_path
bearer = "Bearer "+str(token)
headers = {'Content-Type': 'application/json', 'Authorization': bearer}
fiyat = kart.urun.satis_fiyat
stok = kart.stok
son_kullanma = kart.expiration
barkod = kart.urun.barkod
urun_adi = kart.urun.urun_adi
data = {'price':int(fiyat),'stock':int(stok), 'expiration':str(son_kullanma), 'product':{'name':urun_adi,'barcode':barkod}}
data_json = json.dumps(data)
r = requests.request("POST", str(create_listing_url), json=data_json, headers=headers)
And here is the information from the documentation at server side:
Request Format:
Url: https://staging.lab.xxx.com/api/v1/listings/createlistings
HTTP METHOD: POST
Request Headers:
Content-Type: application/json
Parameters:
[
{
"price": 0, (Required)
"stock": 0, (Required)
"expiration": "2019-06-21T13:37:40.291Z",
"maxCount": 0,
"description": "string",
"isFeatured": true,
"product": {
"id": 0,
"name": "string", (Required)
"barcode": "string", (Required)
"psf": 0,
"vat": 0,
"image": "string"
}
}
]

That solved my problem:
data = [{'price':int(fiyat),'stock':int(stok),'expiration':str(son_kullanma),'product':{'name':urun_adi,'barcode':barkod}}]
r = requests.request("POST", str(create_listing_url), data=json.dumps(data), headers=headers)
data=data wasn't worked for me. Than I followed that answer:
https://stackoverflow.com/a/34051771/11027652

Related

Concatenate Items per Page from Json Path in a dataframe

I have a JSON Path avaliable by Dock API https://lighthouse.dock.tech/docs/cards-and-digital-banking-api-reference/1403b37717e98-list-pix-infractions and its have one limitation of 20 rows or registers per page - MaxItemsPerPage = 20- but i have more than 1000 items - totalItems = 1050.
{
"previousPage": 0,
"currentPage": 0,
"nextPage": 1,
"last": false,
"totalPages": 1,
"totalItems": 1050,
"maxItemsPerPage": 20,
"totalItemsPage": 1,
"items": [
{
"status": "OPEN",
"creditedParticipant": "08706265",
"infractionType": "FRAUD",
"reportedBy": "DEBITED_PARTICIPANT",
"lastModified": "2020-01-17T10:01:00Z",
"debitedParticipant": "99999010",
"creationTime": "2020-01-17T10:00:00Z",
"endToEndId": "E9999901012341234123412345678900",
"reportDetails": "Details that can help the receiving participant to analyze the id",
"responseTime": "2020-01-17T11:00:00Z",
"analysisResult": "AGREED",
"id": "91d65e98-97c0-4b0f-b577-73625da1f9fc",
"correlationId": "evp",
"analysisDetails": "Details of the infraction analysis"
}
]
}
how can i concatenate a set of registers in a multiples pages by period? I have this in python:
import http.client
conn = http.client.HTTPSConnection("pix-baas.caradhras.io")
headers = {
'Content-Type': "application/json",
'Authorization': "334jh89d0"
}
conn.request("GET", "/pix-infractions/v1/list?page=1&from=2020-01-17T10%3A01%3A00Zv&to=2022-01-17T10%3A01%3A00Z", headers=headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

How to fix Kucoin 400 Bad Request - APIs - Python

I wanted to place order limit with my kucoin api using python but all i got is (Bad Request) 400. How do I solve this, please I need help.
here is my code.
stringId = secrets.token_hex(8) #Generating TradeID
url = 'https://api.kucoin.com/api/v1/orders'
now = int(time.time() * 1000)
str_to_sign = str(now) + 'POST' + '/api/v1/orders'
signature = base64.b64encode(
hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"clientOid": stringId,
"side": "sell",
"symbol": "AFK-USDT",
"type": "limit",
"price": "0.05",
"size": "50.00",
}
response = requests.request('post', url, headers=headers)
print(response.status_code)
print(response.json())
This is the error response I got back
400
{'code': '400000', 'msg': 'Bad Request'}
There is a python module called kucoin-python-sdk that does all this for you.
If you would use this library it would boil down to one line like
client.create_limit_order('AFK-USDT', 'sell', '50', '0.05')
If you cannot use this module, you have to follow KuCoin's documentation:
According to KuCoin's documentation, parameters have to be sent in the body of the POST request, not as headers.
So your code should be similar to this:
params = {
"clientOid": stringId,
"side": "sell",
"symbol": "AFK-USDT",
"type": "limit",
"price": "0.05",
"size": "50.00"
}
data_json = json.dumps(params)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json
signature = base64.b64encode(
hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
response = requests.request('post', url, headers=headers, data=data_json)

Add new contact in Xero using python FASTAPI

I am trying to add a new contact in Xero using python FASTAPI:
define a new contact
contact = {
"Contacts": [
{
"Name": "24 locks",
"FirstName": "Ben",
"LastName": "Bowden",
"EmailAddress": "ben.bowden#24locks.com",
"ContactPersons": [
{
"FirstName": "John",
"LastName": "Smith",
"EmailAddress": "john.smith#24locks.com",
"IncludeInEmails": "true"
}
]
}
]
}
Call xero API
get_url = 'https://api.xero.com/api.xro/2.0/Contacts'
response = requests.post(get_url,
headers = {
'Authorization': 'Bearer ' + access_token,
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
},
data = contact
)
json_response = response.json()
I get the following error:
{'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed for this endpoint. This endpoint is expecting Contact data to be specifed in the request body.'}
Someone can help please ?
You can assume that access_token and xero_tenant_id are correct as I am using them for other methods and they works fine.
Thanks
Try to use json = contact instead of data = contact or set header 'Content-Type': 'application/json'
Because
data for dict When not specified content-type, The default is application/x-www-form-urlencoded,

Python to parse nested JSON values that can be null sometimes

I'm trying to parse the following and pull out primary_ip as a variable. Sometimes primary_ip is "null". Here is an example of the JSON, code and the most recent error I am getting.
{
"count": 67,
"next": "https://master.netbox.dev/api/dcim/devices/?limit=50&offset=50",
"previous": null,
"results": [
{
"id": 28,
"url": "https://master.netbox.dev/api/dcim/devices/28/",
"name": "q2",
"display_name": "q2",
"device_type": {
"id": 20,
"url": "https://master.netbox.dev/api/dcim/device-types/20/",
"manufacturer": {
"id": 15,
"url": "https://master.netbox.dev/api/dcim/manufacturers/15/",
"name": "Zyxel",
"slug": "zyxel"
},
"model": "GS1900",
"slug": "gs1900",
"display_name": "Zyxel GS1900"
},
"device_role": {
"id": 4,
"url": "https://master.netbox.dev/api/dcim/device-roles/4/",
"name": "Access Switch",
"slug": "access-switch"
},
"primary_ip": {
"id": 301,
"url": "https://master.netbox.dev/api/ipam/ip-addresses/301/",
"family": 4,
"address": "172.31.254.241/24"
},
Example Python
import requests
import json
headers = {
'Authorization': 'Token 63d421a5f733dd2c5070083e80df8b4d466ae525',
'Accept': 'application/json; indent=4',
}
response = requests.get('https://master.netbox.dev/api/dcim/sites/', headers=headers)
j = response.json()
for results in j['results']:
x=results.get('name')
y=results.get('physical_address')
response2 = requests.get('https://master.netbox.dev/api/dcim/devices', headers=headers)
device = response2.json()
for result in device['results']:
x=result.get('name')
z=result.get('site')['name']
# if result.get('primary_ip') != None
y=result.get('primary_ip', {}).get('address')
print(x,y,z)
I get the following error when I run it:
ubuntu#ip-172-31-39-26:~$ python3 Netbox-python
Traceback (most recent call last):
File "Netbox-python", line 22, in <module>
y=result.get('primary_ip', {}).get('address')
AttributeError: 'NoneType' object has no attribute 'get'
Which value is None? Is it the primary_ip or is it address ?
you could try the following:
y = result.get('primary_ip', {}).get('address, 'empty_address')
This will replace any None values with empty_address
Update:
I have just ran your code and got the following output:
LC1 123.123.123.123/24 site1
q1 172.31.254.254/24 COD
q2 172.31.254.241/24 COD
After running this:
import requests
import json
headers = {
"Authorization": "Token 63d421a5f733dd2c5070083e80df8b4d466ae525",
"Accept": "application/json; indent=4",
}
response = requests.get("https://master.netbox.dev/api/dcim/sites/", headers=headers)
j = response.json()
for results in j["results"]:
x = results.get("name")
y = results.get("physical_address")
response2 = requests.get("https://master.netbox.dev/api/dcim/devices", headers=headers)
device = response2.json()
for result in device["results"]:
x = result.get("name")
z = result.get("site")["name"]
if result.get("primary_ip") != None:
y = result.get("primary_ip").get("address")
print(x, y, z)
I am not sure of the expected output but the code doesn't throw any errors. From looking at the code, it seems there were a few indentation errors, where things didn't match up in terms of where they should have been indented.

Python post api request

I need to make a post into an API. I'm working with python. I'm new on this and I can't create an ad tag. I tried with create a dict with the api example information but it didn't work. When I run the >>> sitios_creados, the answer is ''
and when I run sites.status_codeI reveice `415.
I don't understand why because if you see in my code, I did a right post python requests before with the token
I must to take the publisherid and with it and the token id create the ad tag.
my publisherid is: 15663
my code:
import requests
import json
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ',
}
data = [
('grant_type', 'password'),
('username', ''),
('password', ''),
]
response = requests.post('http://api.site.com/v1/oauth/generateOauthToken', headers=headers, data=data)
json_data = json.loads(response.text)
token = json_data['access_token'].encode("utf-8")
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer {}'.format(token)
}
sites = requests.post('http://api.site.com/v1/inventorymgmt/publisherAdTag?entityId=15663', headers=headers, data=data)
sitios_creados = sites.content
Api information example:
URL: http://api.site.com/v1/inventorymgmt/publisherAdTag?entityId=2685
Method: POST
Request Body:
{
"publisherId": 2685,
"publisherSiteurl": "http://example.org",
"adTagName": "THIS_IS_TEST_DEMAND_5",
"adCodeTypeId": 1,
"foldPlacementId": 1,
"adTypeId": 3,
"pagePlacementId": 1,
"adExpansionDirectionId": 1,
"adSize": {
"name": null,
"width": 0,
"height": 0,
"id": 9
},
"adTagPlacements": [{
"adTagPlacementId": 0,
"linkOnlyToGeo": false,
"ecpm": 1,
"adScript": "THIS IS DEMO SCRIPT",
"currency": 1
}],
"adTagCustomParamMap": [{
"name": "kadcarrier",
"macroValue": "techno.carrier"
}, {
"name": "kadcity",
"macroValue": "geo.city"
}]
}
Is it an API for a website?
When yes, you can do a network analysis in the developer tool of your browser and copy the curl command of the POST package.
Then you surf to curl.trillworks.com and convert the curl command it into a Python POST request.
Inside of your python request you can modify the values.

Categories