POST request can't pass body data from python - json

i am trying to post a request with body to flask REST-api but it doesn't work (Error Response 500), but when i am trying to post it from POSTMAN it works.
body = {
"content_type": "test",
"dc":{
"title": " test",
"is_top": "test",
"position": 0,
"status" : "test"
}
}
headers = {
'Content-Type': 'application/json', 'Accept': 'text/plain'
}
response = requests.post(url, headers = headers, data=body)
i tried with json.dump() also but it was the same result.
POSTMAN CODE (python) that works:
payload = "{\r\n \"content_type\": \"test\",\r\n \"dc\":{\r\n \"title\": \" test\",\r\n \"is_top\": test,\r\n \"position\": 0,\r\n \"status\" : \"test\"\r\n }\r\n }"
headers = {'Content-Type': 'application/json'}
response = requests.request("POST", url, headers=headers, data=payload)

Try this:
body = {
"content_type": "test",
"dc": {
"title": " test",
"is_top": "test",
"position": 0,
"status": "test"
}
}
resp = requests.post(url, json=body)
resp.raise_for_status()

instead json.dump use json.dumps
import requests
import json
postData = { "id" : 1 , "limit":False, "list":[1,2,3] }
response = requests.post("https://abc/api/method",data=json.dumps(postData))
print(json.loads(response.content)

Related

Upload data to server Retrofit 2

i use com.github.ChiliLabs:ChiliPhotoPicker:0.3.1 to select photos to upload. It gives me such a path to the photo
file:///storage/emulated/0/KatePhotos/1641933129.jpg
my code for uploading the image to the server
fun formData(uri: ArrayList<Uri>) {
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("https://httpbin.org")
.build()
// Create Service
val service = retrofit.create(APIService::class.java)
// List of all MIME Types you can upload: https://www.freeformatter.com/mime-types-list.html
// Get file from assets folder
val imgFile = File(uri[0].path)
val fields: HashMap<String?, RequestBody?> = HashMap()
fields["email"] = ("test#test.com").toRequestBody("text/plain".toMediaTypeOrNull())
val filename = imgFile.name
fields["file\"; filename=\"$filename\" "] =
(imgFile).asRequestBody("image/*".toMediaTypeOrNull())
CoroutineScope(Dispatchers.IO).launch {
// Do the POST request and get response
val response = service.uploadEmployeeData(fields)
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
// Convert raw JSON to pretty JSON using GSON library
val gson = GsonBuilder().setPrettyPrinting().create()
val prettyJson = gson.toJson(
JsonParser.parseString(
response.body()
?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
)
)
println(prettyJson)
} else {
Log.e("RETROFIT_ERROR", response.code().toString())
}
}
}
}
The problem is that when I use decoding on the server, I only get a piece of the image. Tell me what I'm doing wrong and how can I fix it?
Its my response:
{
"args": {},
"data": "",
"files": {
"file": "data:image/*;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQECAgMCAgICAgQDAwIDBQQFBQUEBAQFBgcGBQUHBgQEBgkGBwgICAgIBQYJCgkICgcICAj/2wBDAQEBAQICAgQCAgQIBQQFCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAj/wAARCAMABVYDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/90ABAAF/9oADAMBAAIRAxEAPwD+e/A/CinKryOqIjO7EBVAySf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/7QvbS3NlqMrz2FtcPFJL9qS2ezi2mOXEc9xHKwjJVG3JvzlVSipva1/wT/J39E27IuEHJuK3ul6tuS0+cWvXRHyT744o78Ue5r1j4J+EdG8YfEHTbfxVDNN4L063udb1xUcoXsLWFp5Yw45VpBGIlI53SLjmtF3eiWr8ktW/ktTNvtv+vRfM/9L+e/p3o+nFfWOufs82/if4ieND4K1vwz4C+GsXhmDx7aXevXNx5Fpo0726+WrxxSyzPDJdGEgKzuYHA3PhWl8Jfsc/ETxp8T9U+FWg+I/Cl/rkOn6fqtleWllq97ZarZ3kcckE8cttYymCIrPFmS6WBELYYrhsdyb2as9dOul77dbpr5O2zOCy3T07+trP096Ovmr7nyT9aK+qfG/wNgtfg18OvHGgW2m2Ou23h251TxNbvczPcXmNfutOWeJPmjCx7bSJgpT76sA2XYZOofs2XmmaT8Rry7+LPwqj13wrHH/aujquqtcidzGi2scosfsz3BlkaLy/Ozuimb7kbOKi7tqOtm162dtO/wAipQafK9H+vZ9j5s+lFfTXxv8A2Tvit+z/AOHdF8RePba3jtbq7/s6ZI7HUIPsN35XmeUZbm2hhueBJ+8tJJ4sxn58FC3zL+lTGabaT2/r8tfTUlJ2Uuj/AOGA5FGfev0T8N/CL4Zr+zl4M8deI/hv4Ol0q68Ha7quteKI9fujrun6kmoXdpp5h0xLvY1s0yWMDSNaGMeY26VG5GJ8Nf2EvHmo3XwY8UfEW7s/D3w88Qapoq3wax1VJILG+lQQlbwWTWbyzB4o1SKaR43nTzVjVZWj1jD966T6O1+l25K3e/ut7bNPqZynaDn2u7dbJJt9utt99D4HoHp2r7HuP2btS+LviL43698ID4EsfDPhiS6k+waTZeIpbM28Fu8pMd7dWsiRMywygC8nhLyBgg2lBWR8Of2atM1fx98F/CfxJ+KPgjwbe+KNR0oTaChv31e3sLxlaKTfFZTWsUksbRmNXkLKZojIqLuK5UJ+05
},
"form": {
"email": "test#test.com"
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "387553",
"Content-Type": "multipart/form-data; boundary\u003da3942d3b-e13b-43de-9abd-642750914c37",
"Host": "httpbin.org",
"User-Agent": "okhttp/4.9.0",
"X-Amzn-Trace-Id": "Root\u003d1-61ddfc53-4b83816821e2302e6f2b8951"
},
"origin": "",
"url": "https://httpbin.org/post"
}
and so I see what php saves, even notepad considers it to be text.
In decode i see

Getting an error "Can not deserialize instance of java.lang.String out of START_OBJECT " even though the Json code is from Docs

I took this syntax for the payload from the formal docs of jira, yet i am still getting an error. I am using either python or curl both give the same error. I supppose this is a Json related issue , could you find what is wrong with the jason/payload and how do i go about fixing it?
import requests
import json
url = "https://jira.company.io/rest/api/latest/issue/ISS-37424/transitions"
payload = json.dumps({
"update": {
"comment": [
{
"add": {
"body": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"text": "Bug has been fixed",
"type": "text"
}
]
}
]
}
}
}
]
},
"transition": {
"id": "2"
}
})
headers = {
'Authorization': 'Basic YmVzQ=LKKJYTFTgfg','
Accept': 'application/json',
'Content-Type': 'application/json',
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

Post List <int> in http Flutter

I want to send a data like this :
{
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212]
}
To api in flutter. I tried to do that
var data = {
"year": selectedYear,
"class": _classController.text.toString(),
"files": json.encode(carfilesids),
};
final response = await http.post(url, body: data,headers:
{'Accept': 'application/json'});
However there's no errors in run time and when I print the value of json.encoder.convert(carfilesids) it gives me List, I got a response status code of 422 and it tells me " {"message":"The given data was invalid.","errors":{"files":["The files must be an array."]}} ". I also tried to json.encode the whole data but it goes wrong with the other data attributes.
You must use jsonEncode on your map, or else the http package will treat it as form data.
From the documentation:
If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
final response = await http.post(url,
body: {
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212 ]
},
headers: {
'Accept': 'application/json'
}
);

Google Search Console API Error 400 "parseError"

I try to retrieve data from the Google Search Console from Google Apps Script. Here's the script :
var token = getAccessToken()
var siteUrl = "https%3A%2F%2Fpeachday.co"
var payload ={
"startDate": "2020-04-01",
"endDate": "2020-04-21",
"dimensions": [
"query"
]
}
var params = {
'Content-type': 'application/json',
'method':'post',
'headers': {
'Authorization': 'Bearer ' + token
},
'payload':JSON.stringify(payload)
}
var url = "https://www.googleapis.com/webmasters/v3/sites/" + siteUrl + "/searchAnalytics/query";
var response = UrlFetchApp.fetch(url, params)
Logger.log(response)
}
But I get that error
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "This API does not support parsing form-encoded input."
}
],
"code": 400,
"message": "This API does not support parsing form-encoded input."
}
}
Has someone faced that problem ?

Use API's URL to receive json

I am accessing the api of world weather online. I have configured the url and it is displayed below-
http://api.worldweatheronline.com/premium/v1/marine.ashx?key=XXXXXXXXXXXXXXXX&q=-34.48,150.92&format=json
Note: my API key is displayed as XXXXXXXXXXXX and this is returning the following:
{
"data": {
"request": [],
"weather": [
{
"date": "2016-11-20",
"astronomy": [],
"maxtempC": "27",
"maxtempF": "80",
"mintempC": "15",
"mintempF": "58",
"hourly": [
{
"time": "0",
"tempC": "15",
...
I want to GET this json in JS and then log the value of TempC.
How can this be done?
The simplest way would be using request. You can install it with npm install request
const request = require('request')
const apiKey = 'XXXXXXXX'
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
q: '-34.48,150.92',
format: 'json',
key: apiKey
}
request({ url, qs }, (err, response, body) => {
if (err)
return console.error(err)
if (response.statusCode != 200)
return console.error('status:', response.statusCode, body)
body = JSON.parse(body)
console.log(body.data.weather[0].hourly[0].tempC)
})