Doing a POST request on Flutter using the http package

1.3k Views Asked by At

I am trying to hit this endpoint on using flutter. https://docs.particle.io/reference/device-cloud/api/#generate-an-access-token

I've got it working on POSTMAN and curl

curl version: 
    curl https://api.particle.io/oauth/token \
       -u particle:particle \
       -d grant_type=password \
       -d "[email protected]" \
       -d "my_password"

Postman: Authorisation Body

On both curl and postman, I get a response back with the access token.

But when I try to implement this on Flutter I am getting an error response. Here my code on Flutter.

Future<Response> getPublicKey() async {
LoginRequestModel requestModelBody = LoginRequestModel(grantType: "password",
    username: "[email protected]", password: "my_password");
Map<String, dynamic> requestBody = requestModelBody.toJson();
String bodyString = json.encode(requestBody);
//    String formBody = Uri.encodeQueryComponent(bodyString);
print("Body string: "+bodyString);
String url = "https://api.particle.io/oauth/token";
String credentials = "particle:particle";

Map<String, String> headers = {
  HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded",
  HttpHeaders.authorizationHeader: "Authorization $credentials",
};

return await post(url, headers: headers, body: bodyString);

}

The print statement printing out the body string prints out:

{"grant_type":"password","username":"[email protected]","password":"[email protected]"}

This is the error I get back:

{"error":"invalid_request","error_description":"Invalid or missing grant_type parameter"}

I am guessing I am doing the form encoding wrong, but I can't figure out the right way to form encod the body.

Question: How do I hit the REST endpoint documented here using flutter?

1

There are 1 best solutions below

0
On

There's a great website to convert curl commands to Dart code.

Pasting your curl command gives:

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  var uname = 'particle';
  var pword = 'particle';
  var authn = 'Basic ' + base64Encode(utf8.encode('$uname:$pword'));

  var data = {
    'grant_type': 'password',
    '[email protected]': '',
    'my_password': '',
  };

  var res = await http.post('https://api.particle.io/oauth/token', headers: {'Authorization': authn}, body: data);
  if (res.statusCode != 200) throw Exception('post error: statusCode= ${res.statusCode}');
  print(res.body);
}

Comparing with your Postman screenshot seems to indicate that your curl command isn't actually correct, so I'd change it to:

  var data = {
    'grant_type': 'password',
    'username': '[email protected]',
    'password': 'my_password',
  };