Search code examples
flutterrestdartpostxmlhttprequest

http post request returns status code 400


I'm having a problem with the test api post request that I'm doing. I have a post request and before I am receiving a status code of 404 but now it is 400. The way I am testing it is that I am using a local api, you can see it in the url in my post function. I think the 400 error is caused by the data that I am passing is not going through the api like I am passing a null value to the api, but I im not really sure so I dont know what is the problem.

I can add data in the table just fine and I solved the connection problem at first because I cannot connect it to the other pc and I am able to solve it by making the pc discoverable by other devices. but the remaining problem is that it returns error 400, and I think it is because of the passing of data but Im not entriely sure if there is other problem in my code.

Here is the dart file with the post function:

import 'dart:convert';
import 'package:audit_finance_app/widgets/registration_widgets.dart';
import 'package:audit_finance_app/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart';

import '../models/user_info.dart';

class Registration extends StatefulWidget {
  const Registration({super.key});

  @override
  State<Registration> createState() => _RegistrationState();
}

class _RegistrationState extends State<Registration> {
  final firstNameController = TextEditingController();
  final lastNameController = TextEditingController();
  final birthdayController = TextEditingController();
  final genderController = TextEditingController();
  final mobileController = TextEditingController();

  final _formKey = GlobalKey<FormState>();

  RegistrationInfo registrationInfo = RegistrationInfo();

  Future<void> registerUser(RegistrationInfo registrationInfo) async {
    final url =
        Uri.parse('http://192.168.100.228/api/v1/index.php/registration');
    // var uri = Uri.https('192.168.100.228', 'api/v1/index.php/registration');
    try {
      final response = await post(
        url,
        body: json.encode(
          registrationInfo.toJson(),
        ),
      );

      if (response.statusCode == 200) {
        print('User registered successfully!');
      } else {
        print('Failed to register user. Status code: ${response.statusCode}');
      }
    } catch (e) {}
  }

  void getTextFormFieldValue() {
    registrationInfo.first_name = firstNameController.text;
    registrationInfo.last_name = lastNameController.text;
    registrationInfo.birthday = birthdayController.text;
    registrationInfo.gender = genderController.text;
    registrationInfo.mobile = mobileController.text;

    print(registrationInfo.first_name);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('REGISTRATION'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(30, 15, 30, 0),
        child: Column(
          children: [
            Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Widgets().sizedBoxHeight(15),
                  RegistrationWidgets().label(text: 'First Name'),
                  Widgets().sizedBoxHeight(5),
                  RegistrationWidgets().textField(
                    textEditingController: firstNameController,
                    hint: 'Please enter your first name',
                  ),
                  Widgets().sizedBoxHeight(15),
                  RegistrationWidgets().label(text: 'Last Name'),
                  Widgets().sizedBoxHeight(5),
                  RegistrationWidgets().textField(
                    textEditingController: lastNameController,
                    hint: 'Please enter your last name',
                  ),
                  Widgets().sizedBoxHeight(15),
                  RegistrationWidgets().label(text: 'Birthday'),
                  Widgets().sizedBoxHeight(5),
                  RegistrationWidgets().textField(
                    textEditingController: birthdayController,
                    hint: 'Please enter your birthday',
                  ),
                  Widgets().sizedBoxHeight(15),
                  RegistrationWidgets().label(text: 'Gender'),
                  Widgets().sizedBoxHeight(5),
                  RegistrationWidgets().textField(
                    textEditingController: genderController,
                    hint: 'Please enter your gender',
                  ),
                  Widgets().sizedBoxHeight(15),
                  RegistrationWidgets().label(text: 'Mobile Number'),
                  Widgets().sizedBoxHeight(5),
                  RegistrationWidgets().textField(
                    textEditingController: mobileController,
                    hint: 'Please enter you mobile number',
                  ),
                ],
              ),
            ),
            Widgets().sizedBoxHeight(20),
            FilledButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  // do something
                  // Navigator.pop(
                  //   context,
                  //   MaterialPageRoute(
                  //     builder: (context) => const LogIn(),
                  //   ),
                  // );
                  // print(firstNameController.text);
                  // print(lastNameController.text);
                  // print(birthdayController.text);
                  // print(genderController.text);
                  // print(mobileController.text);
                  getTextFormFieldValue();
                  registerUser(registrationInfo);
                  Fluttertoast.showToast(
                    toastLength: Toast.LENGTH_SHORT,
                    msg: 'Registration complete',
                    gravity: ToastGravity.BOTTOM_LEFT,
                    backgroundColor: Colors.grey,
                  );
                  // print('YOU ARE REGISTERED');
                }
              },
              style: FilledButton.styleFrom(
                minimumSize: const Size.fromHeight(50),
              ),
              child: const Text('Register'),
            ),
          ],
        ),
      ),
    );
  }
}

Here is the model:

class RegistrationInfo {
  String? first_name;
  String? last_name;
  String? birthday;
  String? gender;
  String? mobile;

  RegistrationInfo(
      {this.first_name,
      this.last_name,
      this.birthday,
      this.gender,
      this.mobile});

  RegistrationInfo.fromJson(Map<String, dynamic> json) {
    first_name = json['first_name'];
    last_name = json['last_name'];
    birthday = json['birthday'];
    gender = json['gender'];
    mobile = json['mobile number'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['first_name'] = first_name;
    data['last_name'] = last_name;
    data['birthday'] = birthday;
    data['gender'] = gender;
    data['mobile number'] = mobile;
    return data;
  }
}

This is the api documentation:

$app->post('/registration', function () use  ($app){
    //Required Parameters
    verifyRequiredParams(array('first_name','last_name','birthday','gender','mobile'));
    
    //includes
    $database = new Database();
    $conn = $database->getConnection();
    
    //
    $db = new SaveInfo($conn);
    
    $response = array();
    
    $first_name = $app->request->post('first_name');
    $last_name = $app->request->post('last_name');
    $birthday = $app->request->post('birthday');
    $gender = $app->request->post('gender');
    $mobile = $app->request->post('mobile');
    

    $result = $db->savePersonalInfo($first_name,$last_name,$birthday,$gender,$mobile);
    
    if($result){
        $response['error'] = false;
        $response['message'] = "Successfully Registered";
    }
    else{
        $response['error'] = true;
        $response['message'] = "Failed to register";
    }
    echoResponse(200,$response);
});

Here is the working postman request:

Working Postman Request

This is the error message for the 404

{"error":true,"message":"Required field(s) first_name, last_name, birthday, gender, mobile is missing or empty"} Failed to register user. Status code: 400


Solution

  • In postman screenshot you seem to be using form-data. You don't need to json encode your body.

    final response = await post(
            url,
            body: registrationInfo.toJson(),
          );
    

    This answer might help you further - How make a http post using form data in flutter?