How to make api class where api response start with array? - flutter

How to make api class where api response start with array ?
Api Response :-
[
{
"reqList": [
{
"_id": "123448478478",
"username": "12345",
"amount": 4100
},
],
"_id": "636e2c5cf0142eed68343335",
"username": "umesh-rajput",
"amount": 95
}
]

We can handle this response as a list of individual JSON objects inside the response array.
This is general Pseudo code.
class DataProvider{
List<YourModel> getDate(String URL) async {
var response = await http.get(url);
if(resonse.statuscode == 200)
{
var List<YourModel> modelList =
response.body.map((jsonObject)=>YourModel.toJson(jsonObject);
);
return modelList;
}
return [];
}
}

Future<List<MODEL NAME>> getAllBetNotification() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString('userToken');
url = 'API URL';
var response = await http.get(Uri.parse(url), headers: {
'Authorization': 'YOUR TOKEN',
});
if (response.statusCode == 200 || response.statusCode == 201) {
// print(response.body);
var list1 = (jsonDecode(response.body) as List)
.map((dynamic i) =>
UserNotificationModel.fromJson(i as Map<String, dynamic>))
.toList();
return list1;
} else {
print('do not send notification');
return [];
}
}

Related

Infobip SMS bulk messages API with flutter/dart

My post request doesn't work
I've tried running this but i end up with :
{"requestError":{"serviceException":{"messageId":"UNAUTHORIZED","text":"Invalid logindetails"}}}
This is my code :
data() async {
final client = HttpClient();
final request = await client .postUrl(Uri.parse("https://....api.infobip.com/sms/2/text/advanced")); request.headers.set(HttpHeaders.contentTypeHeader, "{'Authorization':'App ...KEY','Content-Type': 'application/json','Accept': 'application/json'}");
request.write({ '"messages": [{"from": "sms","destinations": [{"to": "..."}],"text": "ABC"}]' });
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
}
I just figured out an answer for this POST request in flutter
makePostRequest(int number) async {
final uri = Uri.parse('https://....api.infobip.com/sms/2/text/advanced');
final headers = {
'Authorization':
'App API-KEY',
'Content-Type': 'application/json'
};
Map<String, dynamic> body = {
"messages": [
{
"from": "SenderID",
"destinations": [
{"to": number}
],
"text": "TEST!"
}
]
};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
Response response = await post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
int statusCode = response.statusCode;
String responseBody = response.body;
print(responseBody);
}

DioError [DioErrorType.other]: Converting object to an encodable object failed: _LinkedHashSet len:1 Flutter

I want to print data from the api but i am getting this error below:
DioError [DioErrorType.response]: Http status error [500]
Check the screenshot below from postman, It is working well.
Below is my code, I need help. I get error when I call this function below:
Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
{
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
}
},
options: Options(headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
}));
print(response.data);
print(response.statusCode);
if (response.statusCode == 401) {
// call your refresh token api here and save it in shared preference
await getToken();
signInData(data);
}
} catch (e) {
print(e);
}
}
Hey remove extra { from data inside post method like below -
Future<void> signInData([data]) async {
final prefs = await SharedPreferences.getInstance();
final String token = prefs.getString('token') ?? "";
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
}));
print(response.data.toString());
print(response.statusCode);
if (response.statusCode == 401) {
// call your refresh token api here and save it in shared preference
await getToken();
signInData(data);
}
} catch (e) {
print(e);
}
}

SafeSearch (Google Cloud API) request not returning anything in flutter app

When users upload a photo in my flutter app I want to call the function below to flag inappropriate images. I first upload the image to firebase storage then call this function using the generated image URL. For now, I just want it to print the results to make sure it works but nothing is printed.
static void isAppropriate(String url) async {
const String safeSearchURl =
"https://vision.googleapis.com/v1/images:annotate";
const apiKey = "HIDDEN";
var headers = {
'Content-Type': 'application/json',
'Authorization': 'key=$apiKey'
};
var request = http.Request('POST', Uri.parse(safeSearchURl));
request.body = '''
{
"requests": [
{
"image": {
"source": {
"imageUri": "$url"
}
},
"features": [
{
"type": "SAFE_SEARCH_DETECTION"
}
]
}
]
}''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
}
This is an example of what the printed response should be:
{
"responses": [
{
"safeSearchAnnotation": {
"adult": "UNLIKELY",
"spoof": "VERY_UNLIKELY",
"medical": "VERY_UNLIKELY",
"violence": "LIKELY",
"racy": "POSSIBLE"
}
}
]
}

How to receive the response of a POST request using flutter

I am new to flutter and am trying to receive a response that is returned when I do a post request. I want to display the response object in a preview modal however, i am stuck on how to go about it. I have so far been able to hit the post endpoint successfully and a console.log shows me the response as I expected. How can I receive the response and assign it to a variable that I can then pass to a view modal?
Here is what I have done so far:
/* The Post DbRequest */
Future < Reservation ? > priceReservation(Reservation priceReservation) async {
var content = jsonEncode(priceReservation.toJson());
const baseUrl = ApiEndPoint.baseUrl;
searchUrl = '$baseUrl/reservation/price';
var response = await http.post(
Uri.parse(searchUrl),
body: content,
headers: {
"Content-Type": "application/json"
},
);
final data = json.decode(response.body);
if (response.statusCode == 202) {
print(data);
return data;
} else
print(data);
return null;
}
/* The Post Service */
priceReservation(priceReservation) async {
ReservationDbRequests requests = ReservationDbRequests();
Reservation ? reservation =
await requests.priceReservation(priceReservation);
return reservation;
}
/* How can I receive the response in this save method and assign it the data variable */
_save() async {
if (_formKeyBooking.currentState!.validate()) {
Reservation reservationObject = new Reservation(
roomId: _roomController.text,
email: _emailController.text,
quantity: _quantityController.text.toString(),
checkInDate: DateTime.parse(_checkInController.text),
checkOutDate: DateTime.parse(_checkOutController.text),
);
Response data = await Provider.of < BookingService > (context, listen: false)
.priceReservation(reservationObject);
print(data);
setState(() {
_isLoading = false;
});
toastMessage(ToasterService.successMsg);
} else {
toastMessage(ToasterService.errorMsg);
}
}
// Here is my response
{
"id": "c204b78b-cae3-44ea-9aaf-2f439488fef9",
"email": "adeleke#email.com",
"quantity": 1,
"nights": 5,
"totalPricePerRoomPerNight": 134.07,
"totalPrice": {
"rooms": 615.0,
"discounts": 0.0,
"taxes": 55.35,
"total": 670.35
},
"room": {
"id": "d54986a8-4e00-4332-8edc-acf6e380f6c4",
"name": "villa",
"price": 123.0
},
"checkInDate": "2021-09-29T12:00:00+03:00",
"checkOutDate": "2021-10-04T12:00:00+03:00",
"taxes": [
{
"name": "room services",
"percent": 9.0,
"amount": 11.07
}
],
"discounts": []
}
will this help? check this artilcle for json serilization for complex response
Future <Map<String,dynamic>?> priceReservation(Reservation priceReservation) async {
//you API access code goes here
//check the status first before decoding
if (response.statusCode == 200) { //got the response with data
return json.decode(response.body);
} else if (response.statusCode == 204) { //got the response but no data
return null;
} else { //throw exception for other status code
throw 'error';
}
}
/* The Post Service */
Future<Map<String,dynamic>?> priceReservation(priceReservation) async {
ReservationDbRequests requests = ReservationDbRequests();
Map<String,dynamic>? response =
await requests.priceReservation(priceReservation);
return response;
}
//view
Map<String,dynamic>?> response = await Provider.of < BookingService > (context, listen: false)
.priceReservation(reservationObject);
print(response); //now it should be a Map
if(response != null){
print(response); //all response
print(response['id']); //access id
print(response['email']); //access email
print(response['room']['name']); //access room name
}

Flutter post request parse

I have a POST request:
static String url = 'https://checkout.test.paycom.com/api';
static Map<String, String> headers = {
'Host': 'checkout.test.paycom.com',
'X-Auth': '1234',
'Cache-Control': 'no-cache'
};
Future<Map<String, dynamic>> createCard() async {
try {
Map<String, dynamic> body = {
"id": '123',
"method": "receipts.create",
"params": {
"amount": '2500',
"account": {"order_id": '106'}
}
}
final response = await http.post(url, body: body, headers: headers);
print(response.body);
} catch (e) {
print(e.toString());
}
return null;
}
and give an error
type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'String' in type cast
What I am doing wrong?
your body needs to be as string, best case for you could be convert your body as JSON String as below:
final response = await http.post(url, body: jsonEncode(body), headers: headers);