flutterrestflaskhttp-postget-request

Flutter error when sending post request (even with correct data)


I have a code where I use http package in flutter to post request from a Fake API, which I found using the website mocki.io. The problem is that whenever I put the correct data, it keeps giving me response.statusCode = 405.

http_service.dart (post request)

class HttpService {

  static const _loginUrl = 'https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8';

  static login(cpf, password, context) async {
    Map<String, String> request = {"name": cpf, "city": password};
    final response = await http.post(
      Uri.parse(_loginUrl),
      body: jsonEncode(request),
    );

    if (response.statusCode == 200) {
      await Navigator.push(
          context, MaterialPageRoute(builder: (context) => HomeScreen()));
    } else {
      await EasyLoading.showError(
          "Error Code : ${response.statusCode.toString()} $cpf $password");
    }
  }
}

Inserting the data, according to the fake mocki API: enter image description here Error presented: enter image description here

I would like some help with using Rest API, Flutter and Flask =D. I'll be grateful to those who can send me links about that subject (courses, videos etc).

I tried reading lots of blogs about that same subject, none helped. As I'm novice to that area. =(


Solution

  • The Website you use for creating mock/fake apis mocki.io. As Of now it's only allow GET request you cannot POST on it.

    And You are just doing that just send request with GET method and it will work as expected.

    Here's An Example (using postman):

    GET REQUEST enter image description here

    And now your API calling method will be

    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    class HttpService {
      static const _loginUrl =
          'https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8';
    
      static login() async {
        try {
          // get request
          final response = await http.get(
            Uri.parse(_loginUrl),
          );
    
          print('responseCode : ${response.statusCode}');
          print('responseBody : ${response.body}');
          final result = jsonDecode(response.body);
          print('result : $result');
        } catch (e) {
          print('Error : $e');
        }
      }
    }
    

    Hope this will help you

    Thank you