I'm trying to make a POST request but I keep getting error 400 Bad Request. In Postman it works I have raw body like this:
[
{
"athleteId":"16198",
"departmentId":"3",
"teamId":"278"
}
]
Api request
static Future<List<Athlete>> insertPresences(
int athleteId, int departmentId, int teamId) async {
try {
final response = await http.post(
Uri.parse('https://my_domain/path'),
headers: <String, String>{
'Authorization': 'Basic ..',
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json'
},
body: jsonEncode({
"athleteId": athleteId,
"departmentId": departmentId,
"teamId": teamId
}),
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
if (response.statusCode == 201) {
List jsonResponse = json.decode(utf8.decode(response.bodyBytes));
return jsonResponse
.map((_insert) => Athlete.fromJson(_insert))
.toList();
}
} catch (e) {
logger.e(e.toString());
}
return insertPresences(athleteId, departmentId, teamId);
}
But I'm getting error:
Response status: 400
I/flutter (20754): Response body: {"timestamp":"2022-10-28T12:46:39.969 00:00","status":400,"error":"Bad Request","path":".."}
If someone can explain to me what I'm doing wrong I will be grateful!
CodePudding user response:
You are missing the outer brackets that you show in your raw body. Simply add the brackets, like
body: jsonEncode([{
"athleteId": athleteId,
"departmentId": departmentId,
"teamId": teamId,
}]),