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'
}
);
Related
Is there any way to dynamically include JSON from the request body in the response?
Input Request
{
"id":"1234",
"message":"{\"key\":\"value\"}"
}
Expected Output
{
"status":"CREATED",
"id":"1234",
"message":"{\"key\":\"value\"}"
}
The message and id fields are dynamic and need to be picked from the request.
I have tried the below mapping to dynamically load the response from the request but \" inside message json is converted to "
{
"request": {
"method": "POST",
"urlPath": "/test"
},
"response": {
"status": 200,
"transformers": [
"response-template"
],
"jsonBody": {
"status": "CREATED",
"id": "{{jsonPath request.body '$.id'}}",
"message": "{{jsonPath request.body '$.message'}}"
}
}
}
This returns message as {"key":"value"}.
Even, I have tried changing the mapping to {{{jsonPath request.body '$.message'}}}. But this messes up the whole response json and message value is being returned as "{"key":"value"}" without escape characters.
I'm looking for suggestions to map message dynamically. Thanks in advance.
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+Tl5ufo6erx8vP09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G+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
I'm trying the JSON API provided by DolphinDB, following this tutorial.
And I tried the code snippet like this:
var code = "1+2";
code = encodeURIComponent(code);
paramJson = {
"sessionID": "942605602",
"functionName": "executeCode",
"params": [{
"name": "script",
"form": "scalar",
"type": "string",
"value": code
}]
}
var option = {
url: "http://localhost:9920",
async: true,
data: paramJson,
type: "POST",
dataType: "json",
success: function (data) {
var resultJson = data;
console.log(data);
}
}
$.ajax(option);
Here is the log I got from chrome:
{sessionID: "800870454", userId: "", resultCode: "1", msg: "not a valid json request [sessionID=942605602&func…type%5D=string¶ms%5B0%5D%5Bvalue%5D=1%252B2].", object: Array(0)}msg: "not a valid json request [sessionID=942605602&functionName=executeCode¶ms%5B0%5D%5Bname%5D=script¶ms%5B0%5D%5Bform%5D=scalar¶ms%5B0%5D%5Btype%5D=string¶ms%5B0%5D%5Bvalue%5D=1%252B2]."object: []resultCode: "1"sessionID: "800870454"userId: ""__proto__: Object
It report not a valid json request, but I don't know what's wrong with my request.
You can try serializing JSON objects before sending requests
data = JSON.stringify(paramJson)
I am attempting to retrieve, but not create, tasks from Asana using Google Apps Script.
Using the Asana API Explore, I have constructed a URL that returns the data I desire: https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=987654321987654&completed_since=2018-02-22&limit=100&workspace=456789123456
This URL returns the desired data, in the following format:
{
"data": [
{
"id": 147258369147258,
"assignee_status": "inbox",
"name": "An example task name"
},
{
"id": 963852741963852,
"assignee_status": "upcoming",
"name": "And second example task name."
},
//etc...
]
}
With that URL as a model, I have created a Personal Access Token and executed the following function within Apps Script:
function getTasks5() {
// Asana Personal Token
var bearerToken = "Bearer " + "asdf123456789asdf456789456asdf";
//Request
var request = {
data: {
opt_fields: ["name", "assignee_status"],
assignee: "987654321987654",
completed_since: "2018-02-22",
limit: "100",
workspace: "456789123456"
}
};
// Request options
var options = {
method: "GET",
headers: {
"Authorization": bearerToken
},
contentType: "application/json",
payload: JSON.stringify(request)
};
var url = "https://app.asana.com/api/1.0/tasks";
var result = UrlFetchApp.fetch(url, options);
var reqReturn = result.getContentText();
Logger.log(reqReturn);
}
Instead of returning the desired data as the aforementioned URL does, the function creates an unnamed task in Asana, which is undesirable. It also returns this response containing undesired data:
{
"data": {
"id": 123456789123456,
"created_at": "2018-02-22T20:59:49.642Z",
"modified_at": "2018-02-22T20:59:49.642Z",
"name": "",
"notes": "",
"assignee": {
"id": 987654321987654,
"name": "My Name Here"
},
"completed": false,
"assignee_status": "inbox",
"completed_at": null,
"due_on": null,
"due_at": null,
"projects": [],
"memberships": [],
"tags": [],
"workspace": {
"id": 456789123456,
"name": "Group Name Here"
},
"num_hearts": 0,
"num_likes": 0,
"parent": null,
"hearted": false,
"hearts": [],
"followers": [
{
"id": 987654321987654,
"name": "My Name Here"
}
],
"liked": false,
"likes": []
}
}
Is it possible to simply GET a list of tasks in the manner exemplified by my first JSON example above without creating a task, and without resorting to using OAuth? If so, what changes to the Apps Script function need to be made?
Alright, the problem was with the approach I was taking. Rather than format the request with a payload (which infers a POST request), I needed to structure it more traditionally as a GET request, like so:
var requestUrl = "https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=123456789123&completed_since=2018-02-22&limit=100&workspace=987654321987";
var headers = {
"Authorization" : "Bearer " + AUTH_TOKEN
};
var reqParams = {
method : "GET",
headers : headers,
muteHttpExceptions: true
};
Then I was able to perform:
UrlFetchApp.fetch(requestUrl, reqParams);
And obtain the data I was after.
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)
})