I'm trying to send a POST and I get this error:
{"data":null,"error":{"status":400,"name":"ValidationError","message":"Missing "data" payload in the request body","details":{}}}
In [ ]:
This is my code:
import requests
import json
myToken = '256e8f598edc0990b39dbfe8c4acf39ec83ee3a1a8f212a7656b3892585755c52857503a356ed003fa6b1f5f4b89fc34b0aa64000bb1bf5bba75257a0128365c75aa96a8cb4ed7a32e7fc7b5ec899ae6d2633a7004ef7f991b8ca6e6bdac4a3a75954425f95cc1a209e09272b5582f58690759f81aecb506070c3c19b3cdac2f'
myUrl = 'http://localhost:1337/api/countries'
head = { 'Authorization': 'Bearer {}'.format(myToken), 'Content-Type': 'application/json'}
session = requests.Session()
session.headers.update(head)
Get request & response (working well):
response = session.get(myUrl)
print (response.text)
{
"data":[
{
"id":1,
"attributes":{
"name":"United States",
"createdAt":"2022-04-09T04:15:13.925Z",
"updatedAt":"2022-04-09T04:15:15.226Z",
"publishedAt":"2022-04-09T04:15:15.220Z"
}
}
],
"meta":{
"pagination":{
"page":1,
"pageSize":25,
"pageCount":1,
"total":1
}
}
}
Post request & response:
data = json.dumps(['data', {'name': 'United States'}])
response = session.post(myUrl, data = data)
print (response.text)
{
"data":null,
"error":{
"status":400,
"name":"ValidationError",
"message":"Missing \"data\" payload in the request body",
"details":{
}
}
}
Thanks in advance
I did the solution for that,
First of all: I changed the "data" to "json"
data = {'data': {'name': 'United states'}}
request = session.post(myUrl, json = data)
print (request.text)
Related
I am creating a charge and I want from it to take its 'hosted_url' in order to redirect a user from page.
I am trying to extract it from json, but I newbie and don't know how
...
url = "https://api.commerce.coinbase.com/charges"
payload = {
"local_price": {
"amount": 1,
"currency": USDT
},
"name": "Test for fun",
"description": "Project 2",
"pricing_type": "fixed_price"
}
headers = {
"accept": "application/json",
"X-CC-Version": "2018-03-22",
"X-CC-Api-Key" : "**********",
"content-type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
This is a code to make a request to an api in order to create a charge and in JSON Response I get these fields:
{
"data":{
"code": "123DVAS",
"hosted_url": "https://commerce.coinbase.com/charges/123DVAS",
...
}
}
I want somehow to put this message '123DVAS' in variable or to make a redirect like this:
return render(request, 'https://commerce.coinbase.com/charges/123DVAS')
You can do like this:
# Suppose it's your response looks like this
response = {"hosted_url": "https://commerce.coinbase.com/charges/123DVAS"}
id_fecthed = response.get('hosted_url').split('/')[-1]
# You can redner like this
render(request, f'https://commerce.coinbase.com/charges/{id_fecthed}')
# If you sure that always you want to redirect to hosted_url
# Then you can use this
render(request, response.get('hosted_url'))
Edit:
Full code with data read from requests.
import json
response = requests.post(url, json=payload, headers=headers)
data = json.loads(response.text)
hosted_url = data.get("data",{}).get('hosted_url')
if hosted_url:
id_fecthed = hosted_url.split('/')[-1]
return redirect(f'https://commerce.coinbase.com/charges/{id_fecthed}')
else:
print('Host URL not available')
I'm trying to get url value from the api, but have an issue saying TypeError: string indices must be integers
Here is the array that I get from api:
[
{
"created_utc": 1643524062,
"title": "title",
"url": "https://i.redd.it/tmd5shz9rre81.gif",
},
{
"created_utc": 1643530657,
"title": "title",
"url": "https://i.redd.it/qqjykysxase81.gif",
}
]
And here is the code I use to get the url:
url = "https://reddit-meme.p.rapidapi.com/memes/trending"
headers = {
"X-RapidAPI-Key": "83df5aba87msh4580fa40781b33cp12157bjsnb4b412cb57da",
"X-RapidAPI-Host": "reddit-meme.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
print(response.text[0]["url"])
What am I doing wrong?
response.text is a string, you have to parse it first, with the json librarie, like this:
import requests
import json
url = "https://reddit-meme.p.rapidapi.com/memes/trending"
headers = {
"X-RapidAPI-Key": "83df5aba87msh4580fa40781b33cp12157bjsnb4b412cb57da",
"X-RapidAPI-Host": "reddit-meme.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
data = json.loads(response.text)
print(data[0]["url"])
I would get access to this website, I get it from another website, https://www.betexplorer.com/soccer/algeria/ligue-1/bordj-bou-arreridj-tlemcen/tfvAHu7U/, in the Network section of Developer tools.
Code
import requests
url = 'https://www.betexplorer.com/archive-odds/4urejxv464x0xd4645/18/'
response = requests.get(url, headers={'User-Agent': 'my user agent'})
print(response)
Output <Response [404]>
Set Referer HTTP header to obtain correct response:
import json
import requests
url = "https://www.betexplorer.com/archive-odds/4urejxv464x0xd4645/18/"
headers = {
"Referer": "https://www.betexplorer.com",
}
data = requests.get(url, headers=headers).json()
print(json.dumps(data, indent=4))
Prints:
[
{
"date": "23.07. 17:36",
"odd": "1.88",
"change": "+0.08"
},
{
"date": "23.07. 17:34",
"odd": "1.80",
"change": "-0.01"
},
...
I want to send a multipart/form-data as a post body using python request but I am not getting bad request issue.
import requests
headers = {"Content-Type": "multipart/form-data"}
data = {
"#context": "http://semantro.com/", "#type": "KiranaSearch", "actionName": "listCategoryProducts",
"pageLimit": {"#context": "http://semantro.com/", "#type": "PageProperty", "start": 0, "end": 24},
"data": {"#context": "http://semantro.com/", "#type": "KiranaCategory",
"identifier": "c5394d1d5c6c4cb8-adc77dd996876dba"}
}
response = requests.post('https://merokirana.com/semantro-web-interface/query',
data=data, headers=headers)
print(response.text)
Response
{
"statusTitle" : "ServiceUnsuccessful",
"statusMessage" : "Invalid type of data received. The request should have multipart query data.",
"#context" : "http://semantro.com",
"#type" : "RemoteServiceStatus"
}
But I can retrieve the required data using postman the same formdata.
import http.client
import mimetypes
from codecs import encode
conn = http.client.HTTPSConnection("merokirana.com")
dataList = []
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name=data;'))
dataList.append(encode('Content-Type: {}'.format('text/plain')))
dataList.append(encode(''))
dataList.append(encode("{ \"#context\": \"http://semantro.com/\", \"#type\": \"KiranaSearch\", \"actionName\": \"listCategoryProducts\",\"pageLimit\": {\"#context\": \"http://semantro.com/\", \"#type\": \"PageProperty\", \"start\": 0, \"end\": 24}, \"data\": {\"#context\": \"http://semantro.com/\", \"#type\": \"KiranaCategory\",\"identifier\": \"c5394d1d5c6c4cb8-adc77dd996876dba\"}}"))
dataList.append(encode('--'+boundary+'--'))
dataList.append(encode(''))
body = b'\r\n'.join(dataList)
payload = body
headers = {
'Content-type': 'multipart/form-data; boundary={}'.format(boundary)
}
conn.request("POST", "/semantro-web-interface/query", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
output:
I am getting null response while my code is successfully working. I am not able to get response from dialogAction, i am
import json
import requests
def getdata(intent_name, fulfillment_state, message):
response = {
'dialogAction': {
'type': 'Close',
'intentName': intent_name,
'fulfillmentState': fulfillment_state,
'message': message
}
}
return response
def lambda_handler(event,context):
payload = {'userId':4,'type':'PARENT'}
r = requests.post("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/Tracking/rest/api", data=json.dumps(payload), headers = {'Content-Type': 'application/json','Accept': 'application/json'})
print(r.content)
getdata(
'currentIntent',
'Fulfilled',
{
'contentType': 'PlainText',
'content': 'message'
}
)
From what I understand, your code should be:
import json
import requests
def getdata(message):
return {
'dialogAction':{
'type':'Close',
'fulfillmentState':'Fulfilled',
'message':{
'contentType':'PlainText',
'content':message
}
}
}
def lambda_handler(event, context):
payload = {'userId':4,'type':'PARENT'}
r = requests.post("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/Tracking/rest/api", data=json.dumps(payload), headers = {'Content-Type': 'application/json','Accept': 'application/json'})
print(r.content)
return getdata(r.content)
Let us know if you are getting any error.