Search code examples
iosswiftalamofire

how to create post method cURL request using Alamofire to implement API?


I have the cURL

curl --location --request POST "{{local_url}}/api/customer/registeration" \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --header "device_id: jhjkhkjh" \
  --header "device_type: android" \
  --header "client_id: 1" \
  --header "client_secret: DdoCiociSYHlrjkFrfwfAaNdJcFLjy676ff017zt" \
  --data "name=ram&last_name=sham&mobile_number=7529883763&password=1&role_customer=home%20customer"

I want API implementation for registration using Alamofire in Swift please help me. I tried this the following code but i got error code 422. Help me to fix this.

    let urlString = "{{local_url}}/api/customer/registeration"
            let parameters: [String: Any] = ["name":"Prashant", "last_name": "Kumar", "mobile_number":7814802725, "password": 1, "role_customer": "home%20customer"]
        let headers = ["Content-Type": "application/x-www-form-urlencoded" ,"device_id": "jhjkhkjh", "device_type": "android", "client_id": "1", "client_secret": "DdoCiociSYHlrjkFrfwfAaNdJcFLjy676ff017zt"]
    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
                    if let json = response.result.value {
                        print(json)
                    }
                } 

But i got the result.

{
    data =     {
    };
    error =     {
        code = 422;
        "error_message" =         {
            message =             (
                "The name field is required.",
                "The last name field is required.",
                "The mobile number field is required.",
                "The password field is required.",
                "The role customer field is required."
            );
        };
    };
    status = 0;
}

Solution

  • Your encoding is wrong. JSONEncoding.default is used when you want to send JSON data whereas you are currently sending form data. try to use

    URLEncoding.default