Python post api request - python

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.

Related

Post data (dictionary list) with python requests

I'd like to post my dictionary list below via python's http requests.
my_data=[
{
'kl':'ngt',
'schemas':
[
{
'date':'14-12-2022',
'name':'kolo'
}
],
},
{
'kl':'mlk',
'schemas':
[
{
'date':'23-10-2022',
'name':'maka'
}
]
}
]
trying to do
url='http://myapi.com/product
x=requests.post(url,json=my_data)
after execution it does not post the products on the database
I think when you want to send json payload in post request you should add headers argument:
headers = {'Content-Type': 'application/json', 'Accept':'application/json'}
r = requests.post(url = 'http://myapi.com/product', data = my_data, headers=headers)
response_result = r.text
then check response status code of the post request, If it isn't 200 then post request doesn't completed successfully.

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,

TF400898: An Internal Error Occurred. Activity Id: 1fc05eca-fed8-4065-ae1a-fc8f2741c0ea

i’m trying to push files into git repo via azure API but getting activity_id error. I followed their documentation and trying to add simple file in my repo.
Here is my code:
import requests, base64
pat_token = "xxxx-xxxxx-xxxx"
b64Val = base64.b64encode(pat_token.encode()).decode()
payload = {
"refUpdates": [
{
"name": "refs/heads/main",
"oldObjectId": "505aae1f15ae153b7fc53e8bdb79ac997caa99e6"
}
],
"commits": [
{
"comment": "Added task markdown file.",
"changes": [
{
"changeType": "add",
"item": {
"path": "TimeStamps.txt"
},
"newContent": {
"content": "# Tasks\n\n* Item 1\n* Item 2",
"contentType": "rawtext"
}
}
]
}
]
}
headers = {
'Authorization': 'Basic %s' % b64Val,
'Content-Type': 'application/json',
}
params = (
('api-version', '6.0'),
)
response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo}/pushes', headers=headers, data=payload, params=params)
Anyone knows how to solve this issue? I have also added this issue on their developer community
I’ve fixed that error, actually the payload was not in json format so i have to make it as json and after that it worked fine.
Like this
response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repoId}/pushes', headers=headers, params=params, data=json.dumps(payload))

Getting Converting Value Error While Sending Data With Python Requests Module

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

openstack cannot retrieve authentication token from API

I am trying to retrieve the authentication token from the API using requests library from python. Here is the attempt I have made so far:
def get_token():
data = {
"auth" : {
"identity" : {
"methods" : [ "password" ],
"password": {
"user" : {
"name" : OS_USERNAME,
"domain": { "name": "Default" },
"password": OS_PASSWORD
}
}
}
}
}
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data, # https://stackoverflow.com/questions/9733638
verify = False
)
print(r.content)
j = json.loads(r.content)
return j['token']['user']['id']
I get token in the response :
{
"token": {
"issued_at": "2018-07-03T11:03:59.000000Z",
"audit_ids": [
"Fg1ywtZBQ1CkigCw70If9g"
],
"methods": [
"password"
],
"expires_at": "2018-07-03T12:03:59.000000Z",
"user": {
"password_expires_at": null,
"domain": {
"id": "default",
"name": "Default"
},
"id": "e0dc5beb383a46b98dad824c5d76e719",
"name": "admin"
}
}
}
However, when I am reusing this token to get, for instance, the list of projects :
def get_tenantID():
r = requests.get(
OS_AUTH_URL+'/auth/projects',
headers = HEADERS,
verify = False
)
return r
r = get_token()
HEADERS['X-Auth-Project-Id'] = 'admin'
HEADERS['X-Auth-Token'] = r
r = get_tenantID()
I get this error as if I would not be authenticated:
<Response [401]>
{"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
Googling around and using openstack token issue command showed me that usually, token are more like:
gAAAAABaCo1F1CIMVlsTBeuqYH8tm2qR29tbkmUL4vZuhCNPXJI39TQ2YzL6Twoj8fNcAyLe3WhCYW2O1YpbBF0G8mo4bt7Kf0IRsoDOoJ6uWa3RYyJ5SQNoB_5n8EnVXbKPxFYOZ_iFBnaVtL1_XDrGbwsrlDeyy8lZTDdLsqY52pUhFR-7Uow
which is not what I get with get_token.
What am I doing wrong?
Many thanks!
When you use the auth API directly, the token issued comes in the X-Subject-Token header.
Thus, to retrieve in your python example, you could access the response.headers dict like this:
token = r.headers['X-Subject-Token']
More info about authentication in the Keystone v3 docs
1. fetch authentication token as mentioned below:
r = requests.post(
OS_AUTH_URL+'/auth/tokens',
headers = HEADERS,
json = data,
verify = False
)
token = r.headers[X-Subject-Token]
2. Pass this token in header for further request:
{
'X-Auth-Token': token
}

Categories