Mautic Community Forums

Getting started with Mautic API

Your software
My Mautic version is: 3.3.3
My PHP version is: 7.4
My Database type and version is: MySQL

Your problem
My problem is: Not really a problem, just need some direction…

I think I need the Mautic API to have more flexible integration with my websites/databases on the same server - or will the API take a lot of resources, cause problems, security issues? Should I upgrade to version 4 first; does it have API “built in” or other relevant improvements?

There are different options to install the API library:

Install the Mautic API with Composer. API library is at Packagist. So simple composer require mautic/api-library command will installation of the library to your project for you. Composer will also automatically include the library to your project.

That is kinda awful…

Does it matter where I run composer require mautic/api-library? Should I cd to my mautic folder or will Composer magically dump the files in the right place? Does it matter if I run as root or user?

Composer option is way too scary for me, so let’s try the second option:

Install by git clone

  1. Go to your project folder where you want to place Mautic API library to be. For example:
    cd /var/www/html/myproject
  2. Run git clone to this folder
    git clone git@github.com:mautic/api-library.git .

That looks like a better option, but the knowledge base gives another command:

git clone mautic-api-library

Which is it? Is one old, the other current? Would they both work? Would one mess up my installation?

Edit: I tried Git clone, but get ‘fatal: repository ‘mautic-api-library’ does not exist’ and even worse ‘fatal: destination path ‘.’ already exists and is not an empty directory’ for the version on the developer blog.

Safest solution would be to just download and upload the files:

Copy from ZIP package: Download the library from mautic-api-library-zip. Extract the package to some temporary location. Copy the /lib folder to your project.

But the link to the zip is 404 on both knowledge base and developer blog.

I’ll continue with this in the morning…

I’ve upgraded to Mautic 4. When I now go to Settings / Configuration I can just turn on the API; no mention of having to download an API library. I guess the API is included in version 4, which is great.

Now figuring out how to use it, starting with API Credentials (Applications) in Settings. This looks like the most up-to-date documentation.

Hey there!
The setting to turn on the API has always been there. It’s not something new with Mautic 4.

Have you seen my previous post on the dead links and other BS in your documentation about the API?

I guess the most up-to-date Mautic API documentation is here?

You don’t need to api library to use the api
BS is a really harsh word, it almost sounds like someone claims something works and nothin works.
This is not the case.
You will need a lot of patience with Mautic.
We try to help you here with free support for this free product.

1 Like

It seems, that you don’t fully understand how to use composer or don’t understand how it works.
I suggest to use this great tutorial:

If you use composer in the wrong place, your Mautic will crash
If you use the wrong composer, your library won’t be updated (M4: Composer 2, M2,3: Composer 1)

You don’t need to api library to use the api

@joeyk @rcheesley, so why does your documentation say that you do need a library for the API, with dead links and incomplete, badly written instructions that don’t work?

… you don’t fully understand how to use composer …

I don’t want to use Composer. The promise of Composer is that it makes things easy because it “takes care of everything for you”, but as you indicate, if you “use Composer wrong” stuff crashes and breaks. I prefer to just upload/install files manually. Also, my server and PHP etc. is managed with EasyApache (cPanel); won’t Composer conflict with that?

Edit: I watched the Composer tutorial video. It still does not answer the question whether I should run the Composer command from the documentation as root or as user and whether I should cd to the Mautic directory first or run it somewhere else. They guy from the video even mentions he only knows Windows, does not know how Composer works on Linux.

Is there up-to-date documentation how to use the Mautic API anywhere?

I try to answer you to the best of my knowledge:

Once you clicked you see this:

Make sure you are super patient, and the documentation will show:

Here you can read about all kind of integrations depending on your skill levels.

The API library will speed up development in certain circumstances, but most of the time you are okay using webhooks. Maybe someone wrote, that API library is needed, which is true in certain situations. I’m not sure what you want to do, so it’s really hard to give an advise.

Couple more tips:

  1. Google is your friend
  2. There are really nice people here. The are nice if you are nice.
  3. It’s an open source project. Most of us are not paid or compensated for being here. We are just nice. And we are happy about your success.

So for example if you ask:
How can I send a contact to Mautic from my PHP script, then people will throw scripts at you in no time.

I had seen this documentation. It says I need to install a PHP API library, with a dead link. Is this PHP library included in Mautic 4?

Some Google results for ‘Mautic API’ are these, with the same dead links:

How to Use the Mautic Rest API
What’s Mautic’s API?
Github Mautic API Library

There is a lot of information on authentication with OAuth 1.0a and OAuth 2 or BasicAuth. I think Mautic 4 only has OAuth 2?

I am trying to create a form on my non-Mautic website that posts/updates data to both Mautic and a webinar service - Demio via their API, have that part sorted out.

I guess I should use something like this in my non-Mautic site:

`<?php
use Mautic\MauticApi;
use Mautic\Auth\ApiAuth;

// $initAuth->newAuth() will accept an array of OAuth settings
$settings = array(
‘baseUrl’ => ‘https://your-mautic.com’,
‘version’ => ‘OAuth2’,
‘clientKey’ => ‘5ademokeysdfa6sfas5fas6asdf8’,
‘clientSecret’ => ‘adfdemosecretf3as4f5sf6asfasf97dd’,
‘callback’ => ‘https://your-callback.com
);

// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = “https://your-mautic.com”;
$api = new MauticApi();
$contactApi = $api->newApi(“contacts”, $auth, $apiUrl);
$contact = $contactApi->get($[[contact-id]]);

…`

With this I should be able to get a contact object if I replace $[[contact-id]] with a contact ID? And see what’s in the result with print_r($contact) I guess.

Github has this sample code for ‘Editing an item’:

`$updatedData = [
‘firstname’ => ‘Updated Name’
];

$response = $contactApi->edit($contactId, $updatedData);
$contact = $response[$contactApi->itemName()];

// If you want to create a new contact in the case that $contactId no longer exists
// $response will be populated with the new contact item
$response = $contactApi->edit($contactId, $updatedData, true);
$contact = $response[$contactApi->itemName()];`

So I need something like this, combined with the previous sample code, to post values from my non-Mautic form to Mautic?

There is information on how to generate API credentials here. The Redirect URI is static I assume? I can’t have the form on different sites for different webinars? Or is there a way around that, maybe by adding a variable the last URL part somewhere?

Trying to make something work now and will update with my findings…

Putting the following in another site’s template produces a Fatal Error: Uncaught Error: Class ‘Mautic\Auth\ApiAuth’ not found in … :

`
use Mautic\MauticApi;
use Mautic\Auth\ApiAuth;

// $initAuth->newAuth() will accept an array of OAuth settings
$settings = array(
‘baseUrl’ => ‘https://mysite.com/mautic’,
‘version’ => ‘OAuth2’,
‘clientKey’ => ‘actual_key_here’,
‘clientSecret’ => ‘actual_secret_here’,
‘callback’ => ‘https://otherwebsite.com/test-webinar/
);

// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = ‘https://mysite.com/mautic’;
$api = new MauticApi();
$contactApi = $api->newApi(‘contacts’, $auth, $apiUrl);
$contactobject = $contactApi->get( ‘243’ );

print_r($contactobject);

`

My CMS is looking for Mautic\Auth\ApiAuth in the wrong place; how can I direct it to the right place? What else is wrong?

I’ve tried this Curl approach, based on the code that works for Demio’s API. The goal is to just change the first name for a contact in Mautic with ID 243 from a page in an external site:

`
$mautic_url = “https://mywebsite.com/mautic/api/contacts/”;

$mautic = curl_init($mautic_url);

curl_setopt($mautic, CURLOPT_URL, $mautic_url);
curl_setopt($mautic, CURLOPT_POST, true);
curl_setopt($mautic, CURLOPT_RETURNTRANSFER, true);

$headers = array(
“baseUrl: https://mywebsite.com/mautic”,
“version: OAuth2”,
“clientKey: actual_key_here”,
“clientSecret: actual_secret_here”,
“callback: https://othersite.com/test-webinar/”,
“Content-Type: application/json”,
);
curl_setopt($mautic, CURLOPT_HTTPHEADER, $headers);

$mautic_data = <<<DATA
{
“id”: “243”,
“firstname”: “Changedfirstname”,
}
DATA;

curl_setopt($mautic, CURLOPT_POSTFIELDS, $mautic_data);

//for debug only!

curl_setopt($mautic, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($mautic, CURLOPT_SSL_VERIFYPEER, false);

$something = curl_exec($mautic);

curl_close($mautic);

var_dump($something);
`

This produces the following error:

string(161) “{“errors”:[{“message”:“Looks like I encountered an error (error #400). If I do it again, please report me to the system administrator!”,“code”:400,“type”:null}]}”

Did that error message come from Mautic or my CMS? Is this code communicating with the API - partial success… - or still completely wrong?

How can I make this work? Is there minimum code example how to communicate with the API anywhere?

Trying a brute force approach; just putting this in the address bar:

https://mysite.com/mautic/api/contacts/?clientKey=actual_key&clientSecret=actual_secret&id=243&firstname=Changedname

This results in the following:

{“errors”:[{“message”:“API authorization denied.”,“code”:401,“type”:“access_denied”}]}

What is the minimal example to communicate with the API?

Where are the PHP API files supposed to be? I see I don’t have a folder /api/ in my Mautic installation; which files should I upload where? Or are they somewhere else under another name?

Should I include the API with a line like this - from dodgy years old online info…:

require_once __DIR__ . ‘/lib/Mautic/MauticApi.php’;

Trying to use the Composer way to install the PHP API library that is apparently still required. Running the command composer require mautic/api-library as user, not root, from the Mautic directory, results in following error:

No composer.json in current directory, do you want to use the one at /home/myusername/public_html? [Y,n]?

That’s a no…

What can I try next? Should I copy a composer.json from somewhere else (?) and upload to my Mautic installation folder so Composer can work its “magic”?

Edit:

I copied the composer.json from the API library on Github to my Mautic folder and “simply ran” the magic Composer command again, resulting in the following error message:

Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See Deprecating Packagist.org support for Composer 1.x
Using version ^3.0 for mautic/api-library
Root package ‘mautic/api-library’ cannot require itself in its composer.json

Edit2:

First Composer update attempt with composer self-update --stable

[Composer\Downloader\TransportException]
The “https://getcomposer.org/versions” file could not be downloaded: allow_
url_fopen must be enabled in php.ini (https:// wrapper is disabled in the s
erver configuration by allow_url_fopen=0
failed to open stream: no suitable wrapper could be found)

Edit3:

After enabling allow_url_fopen, Composer self-update runs into permission errors. So this update has to be run as root? Composer self-update to version 2.1.6 went through run as root.

Edit4:

After updating Composer and adding the composer.json and composer.lock from the latest Mautic package to my Mautic installation folder, running composer require mautic/api-library again, again as user instead of root, produces this error:

Using version ^3.0 for mautic/api-library
./composer.json has been updated
Running composer update mautic/api-library
Loading composer repositories witUpdating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Root composer.json requires mautic/core-lib ^3.0 → satisfiable by mautic/core-lib[3.x-dev].
- mautic/core-lib 3.x-dev requires symfony/console ~3.4.0 → found symfony/console[v3.4.0-BETA1, …, 3.4.x-dev] but the package is fixed to v4.4.26 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Edit5:

Trying again with composer require mautic/api-library --with-all-dependencies produces the following error:

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 67108864 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleSetGenerator.php on line 110

Apparently Composer needs a PHP memory limit of 2G, which seems insane to me…

After eventually setting the memory limit to 3G (!), something finally went through, producing the following error:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Root composer.json requires mautic/core-lib ^3.0 → satisfiable by mautic/core-lib[3.x-dev].
- mautic/core-lib 3.x-dev requires willdurand/oauth-server-bundle dev-release-0.0.3 → found willdurand/oauth-server-bundle[dev-master, 0.0.1] but it does not match the constraint.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

Note that Composer is looking for packages required by mautic/core-lib 3.x-dev; I had already upgraded to Mautic 4 and am using the most recent composer.json file I could find.

Edit6:

Apparently Mautic is doubling down on Composer. There is command composer update mautic/core --with-dependencies that looks usable for my situation and maybe I can find an updated composer.json here somewhere?

composer update mautic/core --with-dependencies also requires 3G+ memory in PHP and produces the same errors as before:

Loading composer repositories with package information
Package “mautic/core” listDependency “composer/installers” is also a root requirement. Package has not been listed as an update argument, so keeping locked at old version. Use --with-all-dependencies (-W) to include root dependencies.
Dependency “symfony/var-dumper” is also a root requirement. Package has not been listed as an update argument, so keeping locked at old version. Use --with-all-dependencies (-W) to include root dependencies.
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Root composer.json requires mautic/core-lib ^3.0 → satisfiable by mautic/core-lib[3.x-dev].
- mautic/core-lib 3.x-dev requires willdurand/oauth-server-bundle dev-release-0.0.3 → found willdurand/oauth-server-bundle[dev-master, 0.0.1] but it does not match the constraint.

Note that contrary to these warnings, I already had --with-all-dependencies in the command.

Edit7:

Does it have something to do with this bug? Same bug here - the only page that comes up if you google “willdurand/oauth-server-bundle dev-release-0.0.3”.

@rcheesley had answered this bug with ‘Please ensure that you are using Composer 1 - we will not be supporting Composer 2 until Mautic 4.’ As you can see above, Composer 1 didn’t work; we are now on Composer 2 with Mautic 4.

Where is ‘willdurand/oauth-server-bundle dev-release-0.0.3’ required? I don’t see it in the composer.json for Mautic 4 and can’t find it anywhere in files in my Mautic installation. If I knew where that requirement came from I could try if changing it to 0.0.1 would fix this error.

willdurand/oauth-server-bundle is apparently a ‘Server side implementation of the OAuth 1.0 protocol’. OAuth 1.0 is no longer in Mautic 4. Why is Composer even requiring this?

willdurand/oauth-server-bundle 0.0.3 is required by ‘mautic/core-lib 3.x-dev’. What is ‘mautic/core-lib 3.x-dev’ and should it be in Mautic 4?

Edit8:

Tried again with composer update mautic/core --with-all-dependencies - note ‘all’ included. Still stalls on the same error:

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Root composer.json requires mautic/core-lib ^3.0 → satisfiable by mautic/core-lib[3.x-dev].
- mautic/core-lib 3.x-dev requires willdurand/oauth-server-bundle dev-release-0.0.3 → found willdurand/oauth-server-bundle[dev-master, 0.0.1] but it does not match the constraint.

@rcheesley

Hey there!
The setting to turn on the API has always been there. It’s not something new with Mautic 4.

Is downloading/installing the PHP API library required to use the API?

Is Composer the only way to install that PHP API library?

Is there a fix for this bug?

Is the API documentation still valid for Mautic 4?

Is there a ‘hello world’ code example for the API anywhere?

mzagmajster provided a workaround to install the PHP API library here.

This is a working example of an API call:

require ‘/home/username/public_html/mautic/vendor/autoload.php’;

use Mautic\Auth\ApiAuth;
use Mautic\MauticApi;

$settings = [
‘userName’ => ‘administrator’,
‘password’ => ‘ouou79897password’,
];

$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings, ‘BasicAuth’);

$apiUrl = ‘https://yourwebsite.com/mautic/api/’;
$api = new MauticApi();
$contactApi = $api->newApi(‘contacts’, $auth, $apiUrl);

$id = 243;
$data = array(
‘firstname’ => ‘Donnie’
);

// Create new a contact of ID 243 is not found?
$createIfNotFound = false;

$contact = $contactApi->edit($id, $data, $createIfNotFound);

var_dump($contact);

Put this in a php file, run it in the browser, it will change the first name of your contact with ID 243 to ‘Donnie’.

var_dump($contact) outputs a scary amount of stuff. How can you echo $contact->firstname or $contact['firstname']? Those example don’t work of course.

Can you get a contact by email address instead of ID? Or another field?

There is some documentation here. Is there a complete list of the “options” anywhere?