Post data (dictionary list) with python requests - python

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.

Related

Assign value in json then send it with requests

url = "url"
headers = CaseInsensitiveDict()
headers["Authorization"] = "Bearer mytoken"
headers["Content-Type"] = "application/json"
profile_id='string'
data = """
{
"browsersIds": [
"{{profile_id}}"
]
}
resp = requests.patch(url, headers=headers, data=data)
the problem is that I cannot assign profile_id variable in the JSON therefore i got 400 bad requests
Remove the content type header.
Use json argument with a dictionary rather than needing to create a template string
profile_id='string'
data = {
"browsersIds": [
profile_id
]
}
resp = requests.patch(url, headers=headers, json=data)

Python - API- pagination Graphql

I would like to retrieve data from an API, the problem is that it only returns 49 data each time.
I got the startCursor, hasNextPage and endCursor but I don't know how to tell the script to loop until hasNextPage=False based on the endCursor and thus have all the data for my request.
Here is the code:
import requests
import json
query = """
query {
player(slug:"lionel-andres-messi-cuccittini"){
cards(rarities:[limited]) {
nodes {
slug
userOwnerWithRate {
from
}
}
pageInfo{
startCursor
hasNextPage
endCursor
}
}
}
}
"""
url = 'https://api.sorare.com/graphql/'
r = requests.post(url, json={'query': query})
json_data = json.loads(r.text)
print(json_data)
Do you have an idea to help me get all the pages of a request please?

How can I send this request using python requests library

How to send the below request using python requests library?
Request :
I have tried
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
r = session.post(url, json=json_data)
But it doesn't give the output I want.
1.Define a POST request method
import urllib3
import urllib.parse
def request_with_url(url_str, parameters=None):
"""
https://urllib3.readthedocs.io/en/latest/user-guide.html
"""
http = urllib3.PoolManager()
response = http.request("POST",
url_str,
headers={
'Content-Type' : 'application/json'
},
body=parameters)
resp_data = str(response.data, encoding="utf-8")
return resp_data
2.Call the function with your specific url and parameters
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
key = "123456"
url = "http://somewebsite.com/lib/ajax/service.php?key={0}&info=get_enrolled".format(key)
request_with_url(url, json_data)
With no more info what you want and from what url it is hard to help but.
But try adding headers with the user-agent to the post. More headers may be needed, but User-Agent is a header that is often required.
with requests.Session() as session:
// Some login action
url = f'http://somewebsite.com/lib/ajax/service.php?key={key}&info=get_enrolled'
json_data = {
"index": 0,
"methodname": "get_enrolled",
// And so on, from Request Body
}
headers = {'User-Agent': 'Mozilla/5.0'}
r = session.post(url, json=json_data, headers=headers)

Clarifai: "Malformed or invalid request"

I have the following Python code that makes a POST request to Clarifai's demographics endpoint:
import requests
import pprint
headers = {
"Authorization": "Key MY_KEY",
"Content-Type": "application/json"
}
data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}
proxies = {
"http": "MY_HTTP_PROXY",
"https": "MY_HTTPS_PROXY"
}
response = requests.post('https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs', headers=headers, data=data, proxies=proxies, verify=False)
pprint.pprint(response.json())
Note that I've replaced my real api key and proxies with MY_KEY, MY_HTTP_PROXY, and MY_HTTPS_PROXY respectively.
Does anyone experienced with Clarifai know what I'm doing wrong? I saw an example of working code posted on Clarifai's own forum, but I can't see any major differences between the working code and mine.
Just convert the data passed to json.
import requests
import pprint
import json
headers = {
"Authorization": "Key MY_KEY",
"Content-Type": "application/json"
}
data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}
json_data = json.dumps(data)
proxies = {
"http": "MY_HTTP_PROXY",
"https": "MY_HTTPS_PROXY"
}
response = requests.post('https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs', headers=headers, data=json_data, proxies=proxies, verify=False)
pprint.pprint(response.json())
Needed quotes around the data variable
'data = {"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/demographics.jpg"}}}]}'

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