I tried to send a json data which is populated from hive database using flutter as mobile app and API using Laravel, but my API keep saying that the request is empty.
This is my flutter http.post
Future<void> SendDataBacklog() async {
var jsonBacklog = jsonEncode(backlogList);
final response = await http.post(
Uri.parse('http://109.141.122.292/asmankit-api/api/koko/t1a/input/test'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonBacklog,
);
if (response.statusCode == 200) {
//show your outputs
Hive.box('asmankit_backlog').clear();
AlertPostBerhasil(context);
} else {
print('Backlog data: $jsonBacklog');
print("response backlog: " + response.body);
AlertKoneksiFailed(context);
}
}
This is my json data
[{
"tanggal_catat": "2022-12-08 21:28:18",
"id_mesin": "12",
"hsd": "11",
"rpm": "11",
"tekOli": "11",
"tempMasuk": "11",
"tempKeluar": "11",
"tempMesin": "11",
"r": "11",
"s": "11",
"t": "11",
"kw": "11",
"hz": "11",
"volt": "11",
"cosQ": "11",
"age": "testing| Backlog"
},
{
"tanggal_catat": "2022-12-08 23:22:29",
"id_mesin": "12",
"hsd": "99",
"rpm": "99",
"tekOli": "99",
"tempMasuk": "99",
"tempKeluar": "99",
"tempMesin": "99",
"r": "99",
"s": "99",
"t": "99",
"kw": "99",
"hz": "99",
"volt": "99",
"cosQ": "99",
"age": "testing| Backlog"
}
This is the request response, which say there is no data passed when call the API
response backlog: {"success":false,"message":"Silahkan Isi Data Yang Kosong","data":{"tanggal_catat":["Masukkan Title Post !"],"id_mesin":["Masukkan Title Post !"],"hsd":["Masukkan Content Post !"],"rpm":["Masukkan Content Post !"],"tekOli":["The tek oli field is required."],"tempMasuk":["The temp masuk field is required."],"tempKeluar":["The temp keluar field is required."],"tempMesin":["The temp mesin field is required."],"r":["Masukkan Content Post !"],"s":["Masukkan Content Post !"],"t":["Masukkan Content Post !"],"kw":["Masukkan Content Post !"],"hz":["Masukkan Content Post !"],"volt":["Masukkan Content Post !"],"cosQ":["Masukkan Content Post !"],"kwhProd":["Masukkan Content Post !"],"keterangan":["Masukkan Content Post !"]}}
Last is my flutter mode map toJson
Map<String, String> toJson() => {
'tanggal_catat': waktuCatat,
'id_mesin': idMesin,
'hsd': hsd,
'rpm': rpm,
'tekOli': tekOli,
'tempMasuk': tempMasuk,
'tempKeluar': tempKeluar,
'tempMesin': tempMesin,
'r': r,
's': s,
't': t,
'kw': kw,
'hz': hz,
'volt': volt,
'cosQ': cosQ,
'age': keterangan + "| Backlog",
};
The URL you gave
is not accessible so I am going with your word that it works.
Now since you say print("response backlog: " + response.body); is being hit, that means the if condition of statuscode = 200 is not true.
In general POST requests return a status code of 201 and not 200 when successful. Can you change 200 to 201 and see?
Related
We have a REST service with an incoming REST endpoint that accepts data. It has no web interface (Swagger or so), only the API. With Postman I can POST a JSON file (response code is 202) to it and then read the uploaded data from another endpoint.
When I want to log in to the same endpoint with Cypress to upload a JSON file from the fixtures folder (with the same body as in the Postman request), then I get response code 401 instead – Unauthorized. I have the feeling that the cypress request is wrong because the logfile of the service does not write a message when I use the cypress POST but it does when I use the Postman POST.
First question: What could I be doing wrong in the cypress request?
Second question: Once the authentication works, how can I POST/upload/push the content of the JSON file to that endpoint? Because I have no webpage to interact with, I cannot use click button functions. The documentation mainly deals with interpreting a JSON response but not with sending it.
My cypress code:
it('logs in to connector through REST API', () => {
cy.request({
method: 'POST',
url: 'localhost:8095/connector/demands/v1/demandData',
failOnStatusCode:false,
form: true,
body: {
Username: 'user',
Password: 'pass',
}
})
})
import my-request from '../fixtures/my-request.json'
it('loads the JSON file', () => {
cy.fixture('my-request.json')
})
The structure of the JSON file to upload is not too simple, here is a shortened version:
{
"#metadata": {
"context": "{{A}}"
},
"pool": "{{B}}",
"action": "NEW",
"Type": "ANNOUNCEMENT",
"ON": "Order123",
"PON": "PO123",
"SNN": "SN123",
"direction": "OUT",
"mode": 3,
"pack": [
{
"out": {
"outKey": "OUT14",
"outQuantity": "3",
"dimension": {
"length": "303",
"width": "33",
"height": "903",
"unit": "mm"
},
"layers": "3",
"weight": "3000",
"weightUnit": "grm",
"in": [
{
"inKey": "IN12",
"inQuantity": "3",
"article": {
"articleKey": "article3",
"quantity": "300",
"PON": "Art_PO300",
"SNN": "Art_SN300"
}
}
]
},
"p1": "pack3",
"p2": "pack4",
"store": true
},
{
"out": {
"outKey": "OUT23",
"outQuantity": "5",
"dimension": {
"length": "505",
"width": "55",
"height": "905",
"unit": "mm"
},
"layers": "5",
"weight": "5000",
"weightUnit": "grm",
"in": [
{
"inKey": "IN19",
"inQuantity": "5",
"article": {
"articleKey": "article5",
"quantity": "500",
"PON": "Art_PO500",
"SNN": "Art_SN500"
}
}
]
},
"p1": "pack5",
"p2": "pack5",
"store": true
}
]
}
Solution found. "form: true" must not be given because this overrides the content-type.
You can pass the contents of the fixture file(which is json) in the request body like this:
describe('Some Test Suite', function() {
// we can use these values to log in
const username = 'jane.lane'
const password = 'password123'
it('logs in to connector through REST API', () => {
cy.fixture('my-request.json').then(myFixture => {
cy.request({
method: 'POST',
url: 'localhost:8095/connector/demands/v1/demandData',
auth: {
username,
password,
},
failOnStatusCode: false,
form: true,
body: myFixture
})
})
})
})
For HTTP auth you have to use. You can check out this cypress recipe.
auth: {
username,
password,
}
I am receiving bad request response code (400 for URL) when I am trying to send a json object. I believe I am not passing json object correctly but cannot find where I am doing a mistake.
JSONObject actiontype = new JSONObject();
JSONObject record = new JSONObject();
JSONObject fields = new JSONObject();
JSONObject address = new JSONObject();
actiontype.put("type", "customer");
actiontype.put("action", "create");
record.put("id", "C004");
fields.put("{customerType", "Individual");
fields.put("account", "12345");
fields.put("prefix", "Mr");
fields.put("id", "C004");
fields.put("name", "Deckson and Company Pvt Ltd");
fields.put("firstName", "Deckson");
fields.put("lastName", "Company");
fields.put("email", "test#rcl.lk");
fields.put("telephone", "11235468792");
fields.put("ext", "111");
fields.put("class", "Architecture");
fields.put("paymentMethod", "creditcard");
fields.put("invoiceType", "");
fields.put("vat", "VAT12345");
fields.put("svat}", "SVAT54321");
address.put("{country", "Sri Lanka");
address.put("address", "Rocell");
address.put("street", "No. 20 R.A De Mel Mawatha");
address.put("city", "Colombo");
address.put("postalCode", "003300");
address.put("province", "Western Province");
address.put("isDefaultShipping", true);
address.put("isDefaultBilliing", true);
address.put("isResidential}", false);
record.put("record", address);
record.put("record", fields);
actiontype.put("body", record);
I am expecting to form following json:
{
"type": "customer",
"action": "create",
"record": {
"id": "C001",
"fields": {
"customerType": "Individual",
"account": "21631",
"prefix": "Mr",
"id": "C001",
"name": "Test Customer from Postman",
"firstName": "fN",
"lastName": "lN",
"email": "dekard.shaw#rocell.com",
"telephone": "94775263148",
"ext": "3722",
"class": "Architecture",
"paymentMethod": "creditcard",
"invoiceType": "",
"vat": "VAT21523",
"svat": "SVAT21526"
},
"address": [
{
"country": "Sri Lanka",
"address": "Mr Deckard Shaw",
"street": "No 20, R. A. De Mel Mawatha",
"city": "Colombo",
"postalCode": "00300",
"province": "Western Province",
"isDefaultShipping": true,
"isDefaultBilling": false,
"isResidential": true
}
]
}
}
I noticed a bunch of mistakes:
fields.put("{customerType", "Individual"); // You have a rogue { here.
fields.put("svat}", "SVAT54321"); // You have a rogue } here.
address.put("{country", "Sri Lanka"); // You have a rogue { here.
address.put("isResidential}", false); // You have a rogue } here.
record.put("record", fields); // This should be "fields", not "record".
actiontype.put("body", record); // This should be "record", not "body".
There's also an issue here:
record.put("record", address);
For one, this should be "address", not "record". Additionally, the value needs to be an array, not an object. I don't know what language you're using, but I assume you'll want something that looks like this:
record.put("address", new JSONObject[] { address });
Or maybe this:
JSONArray addresses = new JSONArray();
addresses.put(address);
record.put("address", addresses);
You should take a closer look at the output JSON that you're producing to ensure there aren't more mistakes.
I am using authorize.net's sandbox API to test their gateway in my wix (corvid/code) environment. Funny thing is that when i send JSON to the sandbox API i get a valid JSON response approving the (fake) transaction. however when i set it up thru wix i get data errors in my console. I have built on existing files that i have been able to run basic API responses, and more advanced auths with token responses. so the code works, just not with authorize.net. given my level of expertise, i think it might be something im doing wrong. i've done my due diligence, and there are no questions on this topic. here is my code:
///front end, from the corvid page's code
import {buyIt} from 'backend/authorizeNet';
export function button1_click(event) {
buyIt();
}
pretty basic, just calling code from my backend onClick. the filepath is correct. here is the module on the backend:
//// backend/authorizeNet.jsw
import {fetch} from 'wix-fetch';
export function buyIt() {
let data = {
"createTransactionRequest": {
"merchantAuthentication": {
"name": "***************",
"transactionKey": "****************"
},
"refId": "123456",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "5",
"payment": {
"creditCard": {
"cardNumber": "5424000000000015",
"expirationDate": "2020-12",
"cardCode": "999"
}
},
"lineItems": {
"lineItem": {
"itemId": "1",
"name": "vase",
"description": "Cannes logo",
"quantity": "18",
"unitPrice": "45.00"
}
},
"tax": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"duty": {
"amount": "8.55",
"name": "duty name",
"description": "duty description"
},
"shipping": {
"amount": "4.26",
"name": "level2 tax name",
"description": "level2 tax"
},
"poNumber": "456654",
"customer": {
"id": "99999456654"
},
"billTo": {
"firstName": "Ellen",
"lastName": "Johnson",
"company": "Souveniropolis",
"address": "14 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"shipTo": {
"firstName": "China",
"lastName": "Bayles",
"company": "Thyme for Tea",
"address": "12 Main Street",
"city": "Pecan Springs",
"state": "TX",
"zip": "44628",
"country": "USA"
},
"customerIP": "192.168.1.1",
"transactionSettings": {
"setting": {
"settingName": "testRequest",
"settingValue": "false"
}
},
"userFields": {
"userField": [
{
"name": "MerchantDefinedFieldName1",
"value": "MerchantDefinedFieldValue1"
},
{
"name": "favorite_color",
"value": "blue"
}
]
}
}
}
}
return fetch("https://test.authorize.net/xml/v1/request.api", {
"method": "post",
"headers": {"Content-Type": "application/json"},
"body": data
})
.then(response => {console.log(response.json())});///if response.text is used, it gives details
}
note at the end of the backend code, calling response.json give me a json error, due to the return code contains HTML saying that i've requested invalid data. if i change it to response.text i get this in my console:
//console response with response.text
{...}
isFulfilled:
true
isRejected:
false
fulfillmentValue:
"<HTML><HEAD>\n<TITLE>Bad Request</TITLE>\n</HEAD><BODY>\n<H1>Bad Request</H1>\nYour browser sent a request that this server could not understand.<P>\nReference #7.1d60fea5.1557756725.387c74\n</BODY>\n</HTML>\n"
how do i get a good response from the API? like ive done with the same code in postman?
thanks in advance
return fetch(url, {
method: "post",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(data)
})
.then(response => console.log(response.text())
)
this got me the result i was looking for
stringify() converted my object to a JSON string. i still cannot get it to read the incoming JSON, might have to use parse...but if i read as text i get the info i want and my API is showing a successful transaction.
So I have an api that has a value ("state" : "started"), I want to change to this: ("state" : "done"). If anyone have an idea on how to do this via a http.put request in Flutter, feel free to help :)
API:
GET /api/task/29/
HTTP 200 OK
Allow: GET, POST, PUT, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": 29,
"description": "Berlinmurens Fall",
"state": "started",
"assigned_users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
}
],
"subtasks": []
}
JSON:
{"id":29,"description":"Berlinmurens Fall","state":"started","assigned_users":[{"username":"hugo","fullname":"Hugo Johnsson"}],"subtasks":[]}
Put Request:
putRequest() async {
String url = "--URL--";
final Map<String, dynamic> jsonDataaa = {
"state": "done"
};
var response = await http.put(
Uri.encodeFull(url),
headers: { "Accept" : "application/json"},
body: json.encode(jsonDataaa),
encoding: Encoding.getByName("utf-8"),
);
return response;
}
What I'm trying to do:
final Map<String, dynamic> jsonDataaa = {
"id": 29,
"description": "Berlinmurens Fall",
"state": "done",
"assigned_users": [
{
"username": "hugo",
"fullname": "Hugo Johnsson"
}
],
"subtasks": []
};
you can use patch method in flutter for sending single field.
look this link Http-Methods in flutter
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})