Mautic Community Forums

Need help with Mautic API and BasicAuth

My Mautic version is: 2.16
My PHP version is: 7.2

Hello there, I’m trying to use mautic’s api to update contact field dynamically. I cannot use Oauth since the token(s) are expiring and I don’t want to generate new tokens since it’s should be “always working”.
I would like to use BasicAuth for this purpose, and I downloaded the example code.

My problem is: how do I set up basic auth for mautic ? If I create an htaccess + htpasswd to the mautic base url, every visitor of my website will get a prompt asking for password since I embed the mautic tracking script (?). I get all the time an error “401 Unauthorized”, probably because I have not linked a username and password to the API.
How do I proceed?
Thank you.

These errors are showing in the log: 401: The response has unexpected status code (401). Access denied.

Steps I have tried to fix the problem: read every single API documentation pages, searched all over Internet and didn’t find this specific problem.

Hi basic auth is a USER :slightly_smiling_face:

So this is what you do:

  1. Turn on basic auth on your config
  2. Create a user with username and psw
  3. REBUILD CACHE (important)

Than you can api in with basic auth. Example in php:

$curl = curl_init();
    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => "https://".$loginname.":".$password."@".$siteurl."/api/contacts/new",
            CURLOPT_USERAGENT => 'Randomguy Software Api Call',
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => array(
            'email'  => $email,
            'firstname' => $firstname,
            'lastname' => $lastname,
            'order_time' => date("Y-m-d H:i:s")
            )
    ));
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    // Close request to clear up some resources
    curl_close($curl);
    };  

Good luck!
Joey

1 Like

Hello joeyk!
Perfect answer, thank you very much, I just found out it was the username of a user 2 seconds before your answer haha!
I was searching too far…
So I guess I will create a user for this specific purpose instead of using the administrator account.
Thank you again.