I'm trying to convert my python code to flutter, but unable to do so. Trying to perform put request to update data on the website. Here is my original put request written in python.
import requests
url = "https://my.website.com/api/request/12"
headers = {"user_key":"kfrrt-000234-as12321-1h58dm66a"}
input_data = '''{
"request": {
"comment": "New comment",
"status": {
"request_status": "Open"
}
}
}'''
data = {'input_data': input_data}
response = requests.put(url,headers=headers,data=data,verify=False)
What I have so far in flutter :
postTaskInfo()async{
var jsonMP= {'request": {"comment": "New comment","status": {"request_status": "Open"}}'};
String jsonString= jsonEncode(jsonMP);
var url = 'https://my.website.com/api/request/12';
await http.put(url, body: jsonString, headers: {"user_key":"kfrrt-000234-as12321-1h58dm66a"} ).then((response){
setState(() {
print(response.body);
});
});
}
I get an error " Unhandled Exception: Converting object to an encodable object failed: Instance of '_CompactLinkedHashSet
Thank you !
The problem occurs due to jsonEncoding failed to encode non-json data to string, so correct the jsonMP variable.
yours:
var jsonMP= {'request": {"comment": "New comment","status": {"request_status": "Open"}}'};
Should be in the form of
var jsonMP = {
"request": {
"comment": "New comment",
"status": {"request_status": "Open"}
}
};
Related
I have a Json data, where I want to get the value of "authorization" i.e "OToken
DEDC1071B77800A146B6E8D2530E0429E76520C151B40CC3325D8B
6D9242CBA3A6BFA643E7E5596FBEBAE0F46A1FB1BCD099EBC1F59D
CD82F390B6BC45FCE036F37F7F589BD687A691E1378F1FF432331C
62E7E641E857C8F8A405A4BFE2F01B1EB8F3C69817D45F5DDE9DEE
346ACABA1B7208DECA9E43CCE7AB3761553E23D9CB36A870C1819C
15C7C4B1CFE2802DFD05F651AA537AB81787.4145535F55415431" using python
{
"links":[
{
"method":"GET",
"rel":"self",
"href":"https://www.sampleurl.com/request"
},
{
"headers":{
"authorization":"OToken
DEDC1071B77800A146B6E8D2530E0429E76520C151B40CC3325D8B
6D9242CBA3A6BFA643E7E5596FBEBAE0F46A1FB1BCD099EBC1F59D
CD82F390B6BC45FCE036F37F7F589BD687A691E1378F1FF432331C
62E7E641E857C8F8A405A4BFE2F01B1EB8F3C69817D45F5DDE9DEE
346ACABA1B7208DECA9E43CCE7AB3761553E23D9CB36A870C1819C
15C7C4B1CFE2802DFD05F651AA537AB81787.4145535F55415431"
},
"valid_date":"2020-08-17T15:49:00+0530",
"method":"POST",
"rel":"redirect",
"href":"https://www.billdesk.com/pgi/MerchantPayment/",
"parameters":{
"mercid":"BDMERCID",
"bdorderid":"OAFC19XTFD8TSP"
}
}
]
}
import json
response = YOUR_JSON_STRING
data = json.loads(response)
authorization = data['headers']['authorization']
I'm building an mapping app using cordova and making a post request sending the following JSON (feature)
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-6.6865857,
53.2906136
]
},
"properties": {
"amenity": "pub",
"name": "The Parade Ring"
}
}
This is the JQuery code sending the request
function savePub(feature){
$.ajax({
type: "POST",
headers: {"csrfmiddlewaretoken": csrftoken},
url: HOST + URLS["savePub"],
data: {
pub_feature: JSON.stringify(feature)
},
contentType:"application/json; charset=utf-8"
}).done(function (data, status, xhr) {
console.log(data + " " + status);
pubDialogAlert("Pub saved",feature);
}).fail(function (xhr, status, error) {
showOkAlert(error);
console.log(status + " " + error);
console.log(xhr);
}).always(function () {
$.mobile.navigate("#map-page");
});
}
When the request is received in the Django backend I am not sure why when I print the request body it looks like this,
b'pub_feature=%22%7B%5C%22type%5C%22%3A%5C%22Feature%5C%22%2C%5C%22geometry%5C%22%3A%7B%5C%22type%5C%22%3A%5C%22Point%5C%22%2C%5C%22coordinates%5C%22%3A%5B-6.6865857%2C53.2906136%5D%7D%2C%5C%22properties%5C%22%3A%7B%5C%22amenity%5C%22%3A%5C%22pub%5C%22%2C%5C%22name%5C%22%3A%5C%22The+Parade+Ring%5C%22%7D%7D%22'
and when I try to decode it and then use json.loads() it throws this error
#api_view(['POST'])
def save_pub(request):
if request.method == "POST":
data = request.body.decode('utf-8')
received_json_data = json.loads(data)
return Response(str(received_json_data) + " written to db", status=status.HTTP_200_OK)
JSONDecodeError at /savepub/
Expecting value: line 1 column 1 (char 0)
I am assuming because once it decodes the binary string it can't be converted to valid JSON because of those characters %22 etc, but I don't know what the solution is.
Any help would be appreciated.
Thanks
You're mixing up two things here, form-encoded and JSON format. What you have is a form-encoded post with one key, pub_feature, whose value is a JSON object.
Instead you should post the JSON directly:
data: JSON.stringify(feature),
and then you should be able to load it as you do already - although note that really you should let DRF deal with that for you
I'm trying to do a basic Bitly shortening URL call. However, I cannot seem to either push the json correctly, or deal with the json response correctly... I omitted some obvious variables for brevity and obfuscated some real values for security purposes.
import requests
import json
bitly_header = {'Authorization':'Bearer
some_long_secret_character_string_here', 'Content-Type':'application/json'}
bitly_data = {
"long_url": ""+long_url+"",
"group_guid": ""+bitly_guid+""
}
short_link_resp =requests.post(bitly_endpoint,data=bitly_data,headers=bitly_header)
short_link_json = short_link_resp.json()
short_link = short_link_json["link"]
Errors is "Key error: 'link'
The json I get from Postman is:
{
"created_at": "1970-01-01T00:00:00+0000",
"id": "bit.ly/2MjdrrG",
"link": "bit.ly/2MjdrrG",
"custom_bitlinks": [],
"long_url": "google.com/",
"archived": false,
"tags": [],
"deeplinks": [],
"references": {
"group": "https://api-ssl.bitly.com/v4/groups/Bi7i8IbM1x9"
}
}
try replace data with json:
short_link_resp =requests.post(bitly_endpoint, json=bitly_data, headers=bitly_header)
see the doc ref.
I'm trying to send a json in POST method using REST, but i got error:
"Could not parse JSON data: Expecting value: line 1 column 1
(char 0)", "status": 500, "type": "ValueError",
"request": {"client_addr": "127.0.0.1",
"user_agent": "python-requests/2.3.0 CPython/3.4.2 Linux/3.16.0-41-generic",
"method": "POST", "path": "/api/adley/doc"}}
)
I'm trying to fix, use a json.dumps or json.loads, but nothing seems to work.
I need to send one key and two values. Here is the base:
{
metadata: {
idx_exp: false,
idx_exp_time: 0,
file_ext: false,
password: "",
description: "base de teste",
idx_exp_url: "",
model: {
item: "Text"
},
dt_base: "29/06/2015 14:47:10",
name: "adley",
id_base: 5,
file_ext_time: 0,
},
content: [
{
field: {
required: false,
multivalued: false,
alias: "Texto",
datatype: "Text",
name: "item",
indices: [
"Ordenado"
],
description: "placeholder"
}
}
]
}
My to send a post script:
import requests, json
url = "http://127.0.0.1/api/adley/doc"
json_data = {'value':{'item':'test'}}
response = requests.post(url, params=json_data)
print(response.text)
I can't see what's wrong with my script
try passing the data parameter instead of the params parameter to the post method. requests wants to url encode params where you want the json data. So something like this:
requests.post(url, data=json.dumps(json_data))
Hi I am using urrlib2 to send some data and custom headers to a link. Am getting 500 internal server error. I have contacted the service, and they are saying the data(json data) is correct but there is some error in my python code. What am I doing wrong ?
Following is the code.
import urllib2,urllib
import json
PREPAYMENT_URL = "https://services.gharpay.in/rest/GharpayService/"
PREPAYMENT_USERNAME = "somename"
PREPAYMENT_PASSWORD = "somepass"
data = {
"customerDetails":{
"address": "ads",
"contactNo": "9663924147",
"email": "a#c.com",
"firstName": "akash",
"lastName": "deshpande",
"prefix": "Mr."
},
"orderDetails" : {
"pincode": "411036",
"clientOrderID": "21234",
"deliveryDate": "13-10-2013",
"orderAmount": "123",
"clientComments": "please be carefull",
"paymentMode": "Cash",
"productDetails": {
"productID": "21334",
"productQuantity": "1",
"unitCost": "123",
"productDescription": "tshirt"
},
"templateID": ""
},
}
def create(request):
function = 'createOrder'
url = PREPAYMENT_URL
url = url+ function
headers= {'username':PREPAYMENT_USERNAME,'password':PREPAYMENT_PASSWORD,'Content-type':'application/json'}
data1 = urllib.urlencode(data)
req = urllib2.Request(url,data1,headers)
try:
contents = urllib2.urlopen(req).read()
except urllib2.HTTPError as e:
error_message = e.read()
print error_message # this error message is being printed. It is showing 500 error.
Your code is perfect except for one teensy-weensy detail:
The header should be Content-Type, not Content-type.
Maybe try changing this header and let me know if it works!