Solved How do you handle API error using curl/bash example ?

MaXi32

Verified User
Joined
Jul 25, 2016
Messages
645
Location
The Earth
I have the following code to add admin account via API using bash/curl. Code is working good but I'm not so sure how to get the return status:

Bash:
#!/bin/bash


function cmd_api_account_admin() {


action="$1"
username="$2"
email="$3"
password="$4"
DA_ADMIN_USERNAME="admin"
DA_ADMIN_USERPASS="password"
DA_HOSTNAME_FQDN="server.domain.com"
DA_PORT="2222"

data="action=${action}&add=submit&username=${username}&email=${email}&passwd=${password}&passwd2=${password}&notify=yes"
curl --request POST --user "${DA_ADMIN_USERNAME}":"${DA_ADMIN_USERPASS}" --data "${data}" "https://${DA_HOSTNAME_FQDN}:${DA_PORT}/CMD_API_ACCOUNT_ADMIN"
}
cmd_api_account_admin "create" "admin2" "[email protected]" "123456"
if let say the username is incorrect, I can view this error using directadmin debug mode (running DA in debug mode). But how do you get the error code through curl request in this script?

Bash:
curl --request POST --user "${DA_ADMIN_USERNAME}":"${DA_ADMIN_USERPASS}" --data "${data}"
retval=$?
echo "$retval"

I've tried adding return code $? as above but it just returns 0 (success) eventhough the request is not success. In PHP I saw example how to handle the error code but in bash I've not seen many example for this.
 
Last edited:
Sorry I think I got it. didn't notice the error=0 output there when it's success (but it wont output if error and I just got bunch of HTML code). So I just need to grep this value to determine it's success or not.api.PNG

EDIT: I think I might have done something wrong earlier, it actually did output error=1 when it has error for example adding the same username. solved.
 
Last edited:
Back
Top