For hosts with no Composer. How to add the API to a php script with require?

Hey, everyone.

Our shared hosting does not provide Composer as a part of the account so we manually require all the plugins ourselves.

What do we need to require("") to load mautic’s api?
I tried searching the folders for api directory but could not find anything relevant I could autoload.

Hi, i’m also starting to learn how to work with the API. I’d like to send mails with slightly changing content to a segment. Therefore i gather some infos from a external form and trigger sending via API.

As far as i understand one needs to gather the api-libary, which can also be done by downloading the source from the git repository

and unzip ist. Rename the folder created into “lib” and point your require into this.

Composer builds a autoload package and download not. So you may need to include more sources…

I have been wrestling with this here, dragged into Composer hell, still stuck.

I use API without the API library. So much easier.

How does that work? All the Mautic API documentation that I have been able to find refers to a library that has to be installed and/or an /api/ directory that does not exist in my current Mautic 4 installation.

How to Use the Mautic Rest API
Mautic Developer Documentation

Is there a basic ‘hello world’ Mautic API code example anywhere? I have not been able to piece it together with the clues in the documentation.

Either way, is the library required? Optional? Now integrated in Mautic 4? Can someone please clarify. I am not the only one confused about this.

I make a video for you.

Never thought to hear you saying that Joey :wink: But glad to know i’m not the only one doing so. To be honest i’ve written a small class having all i need in my tools/scripts as abstract functions and also found it much easier to use than the official PHP lib.

I won’t do that in the video, but maybe 3-4 exaples would be nice.
However this is what happens 99% of the time:

  1. Enable API and add credentials
  2. Test api and realize it doesn’t work. 404 Error.
  3. Check the folder structure, and realize there is no /api/ folder
  4. Read the docs, watch videos, read the docs
  5. Go through all the 5 stages of grief
  6. Find a post, that finally mentions that YOU ALWAYS CLEAR CACHE
  7. Clear Cache
  8. API works
1 Like

How do I test the API? A ‘hello world’ example would be helpful.

Do you use Postman for API testing?
Or a PHP snipplet would brighten your day?

1 Like

Yes, a PHP snipplet would please us. Never heard of Postman - wasn’t that an email client?

Postman is an API testing tool. It is a true delight to use.
https://www.postman.com/

Snipplet to create a contact with simple identification:

Start your code with defining the variables:

<?php
$loginname = 'apiuser';
// Loginname of your API user
$password = 'yourpasswordhere';
// This is the password of the API user
$siteurl = yoursiteurl.tld;
// example: mymautic.com

Add the payload:

$email = 'captain_enterprise-d@starfleet.com';
$firstname = 'Jean-Luc';
$lastname = 'Picard';
$tag = 'purchased';

And execute the API call:

$curl = curl_init();
// Set some options - we are passing in a user agent too here
  curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL => "https://".$loginname.":".$password."@".$siteurl."/api/contacts/new",
  CURLOPT_USERAGENT => 'Mautic Connector by Joey',
  CURLOPT_POST => 1,
// posting the payload
  CURLOPT_POSTFIELDS => array(
    'firstname' => $firstname,
    'lastname' => $lastname,
    'email' => $email,
    'tags' => $tag
  )
));
curl_exec($curl);

That’s it.

If you go with Postman, here are a bunch of API scripts as a Postman collection:

2 Likes

Thanks! That looks like something I can work with. Will try this tonight and report back… (I won’t get to this until the weekend…)

Super important: your custom fields have to be publicly updateable in order to update from API

image

1 Like

@joeyk, what is ‘the API user’? The Mautic admin or other system users? Or should I set up ‘the API user’ somewhere else?

Should the API credentials not be used anywhere here?

I still don’t have a folder /api/ - clearing the cache does not fix that of course, so I don’t understand that point in your instructions.

What is that ‘user agent’? Is it required? Totally random?

Here is what I put into a template file of my other site - it should fire if you put ?accesscode=something in the URL and then change the firstname of an existing contact identified by email to ‘Ronnie’:

<?php
if ( isset( $_GET['accesscode'] ) ) {
echo $_GET['accesscode'];

// Loginname of your API user
$loginname = 'administrator';
// This is the password of the API user
$password = 'passwordformauticadmin';
// example: mymautic.com
$siteurl = 'https://mywebsite.com/mautic';

$email = 'existing@emailaddress.com';
$firstname = 'Ronnie';

$curl = curl_init();
// Set some options - we are passing in a user agent too here
  curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL => "https://".$loginname.":".$password."@".$siteurl."/api/contacts/new",
  CURLOPT_USERAGENT => 'Modified Mautic Connector',
  CURLOPT_POST => 1,
// posting the payload
  CURLOPT_POSTFIELDS => array(
    'firstname' => $firstname,
    'email' => $email,
  )
));
curl_exec($curl);
}

The accesscode gets echoed, but nothing else happens; the name of the contact is not changed to Ronnie.

Hi,

when you enabled Basic auth. in your mautic instance you can send requests as any user that has sufficient rights (so yes, admin should work).

I would suggest you create dedicated account in mautic you will use just for api calls, but for testing faze does not really matter.

User agent is just a string send with a request so that application making the requests “presents” itself to the server, I do not think it really matters in this situation (btw. User agent is something typical browser sends with every request).

Now about the comoser and mautic api library: If you do not have composer on your hosting do you maybe have admin privileges and ssh access? If you do, you can install composer (and later api library) manually.

And lastly about your code above. Can you echo out curl_error so we see what actually goes wrong?

If your url is https://mywebsite.com/mautic and your trying to edit existing contact you should call:

https://mywebsite.com/mautic/api/contacts/{contactUd}/edit with request type set to patch.

On the other hand if you are trying to create new contact I can see that offical docs specify more parameters in leead creation process (maybe request fails because you did not pass all the required params, see here: < Mautic Developer Documentation >).

1 Like

@mzagmajster, thank you for your response. As far as I know Mautic 4 no longer has the Basic Auth option, only OAuth 2.

I have Composer on my VPS and have no problem using it, but it is stuck on a Mautic bug. Attempts history here.

Previously reported Composer bug here.

Can you echo out curl_error so we see what actually goes wrong?

I have no clue where to do that, but am pretty sure what goes wrong is 1) I can’t connect because Mautic 4 does not have Basic Auth and 2) there is no /api/ directory in my installation, which is probably part of the fabled PHP API library that can only be installed via the magical Composer that fails on an unsolved Mautic bug.

Looks like M4 allows basic auth.:

Lets make some things clear first:

  • the way mautic is built you do not actually need api directory since app itself registers all /api endpoints
  • mautic php library is just a wrapper around curl functions you used above to make usage of the mautic api easier. In other words: mautic api library does not provide any logic or functionality to core mautic api endpoints
  • You can put curl_error($curl); after curl_exec function call to get text representation of the last error.
  • The previous posts you linked too make me believe that you did not install Mautic from source but from pre-prepaired release, I strongly suggest you install mautic from github since having mautic under git (have clone of official repo. provides you with some additional info as well as some other stuff, but lets not get into that now :)).

So here is the snippet I used to update lastname of the contact on Mautic 4.0.0, using mautic api library This script should not be used in prod. environment, its for testing purposes only.:

<?php

// Bootup the Composer autoloader
include __DIR__ . '/../vendor/autoload.php';  // Make sure you actually specify correct path here!!!

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

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = [
    'userName'   => '<YOURVALUE>',             // Create a new user       
    'password'   => '<YOURVALUE>',             // Make it a secure password
];

// Initiate the auth object specifying to use BasicAuth
$initAuth = new ApiAuth();
$auth     = $initAuth->newAuth($settings, 'BasicAuth');

// Nothing else to do ... It's ready to use.
// Just pass the auth object to the API context you are creating.

// Create an api context by passing in the desired context (Contacts, Forms, Pages, etc), the $auth object from above
// and the base URL to the Mautic server (i.e. http://my-mautic-server.com/api/)

$apiUrl = '<YOURVALUE>';
$api        = new MauticApi();
$contactApi = $api->newApi('contacts', $auth, $apiUrl);


$updatedData = [
    'firstname' => 'Ronnie'
];
$contactId = <YOURVALUE>;

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

// Just to show stuff...

echo "<pre>";
var_dump($contact);
echo "</pre>";

After you edit it a little bit, you should be able to call your api, but please look at the next chapter before trying to use this script.

Since I said before that I suggest installing Mautic from source, here are steps I suggest you take to get Mautic and library up and running:

  • First backup your database and entire directory where you have mautic installed.
  • Install git on your server if you do not have it already.
  • Clone official Mautic repo. git clone…
  • Move to mautic dir.
  • git fetch origin features
  • git checkout features
  • git pull origin --tags
  • git checkout 4.0.0 # I assume you run Mautic 4.0
  • Copy app/config/local.php from backup to new mautic dir (mautic/app/config)
  • composer install --no-dev # Please see notes at the bottom before you run this.
  • Finally run composer require mautic/api-library to install Mautic library # Once this is installed you can actually run the script above

Notes:

  • I had some issues while installing composer packages in development instance and solved it, by removing "bin-dir": "bin", from composer.json config object. If you run into issues while installing the packages please try to remove it.

Hope this helps.

1 Like

Thanks for the additional clues @mzagmajster

I installed Mautic a few years ago now, have been using it in production and am not going to reinstall the whole thing. I have been getting the upgrade files from Github since Mautic 2. Why is “installing Mautic from github source” - whatever that means - so fundamentally different from what I have now and is there no way for Mautic to fix those differences in their upgrades? I have to reinstall my production CRM for what exactly; that willdurand/oauth-server-bundle Composer bug? I don’t get it.

The line ‘use Mautic\Auth\ApiAuth;’ causes a 500 Internal Server error:

syntax error, unexpected ‘use’ (T_USE) (line 78

Apparently use can only be used at the top of the page. One error fixed. Next error is:

Fatal Error: Uncaught Error: Class ‘Mautic\Auth\ApiAuth’ not found in /home/username/public_html/myothersite/site/assets/cache/FileCompiler/site/templates/session.php:92

So my line here is not working I guess:

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

Or would it work if I reinstalled everything from Github source or found another way to get Composer beyond that bug to install the fabled PHP API?

@modifiedcontent

So I suggested you install it by cloning repository from github because it seems like the easiest way to me (I may have been wrong).

You actually do not re-install the CRM in real sesne, you just organize the whole project setup in a way, that you can easily mange the dependencies. I mean after all before I wrote you the answer I started out from simple source clone from github. But I understand that might not be the most convenient thing for you. The good news is that that should not be a deal breaker.

If you want to keep your source and your update process intact, you can just go and try to install mautic api library differently (again I do not know your situation, so this might not be suitable for you):

  • Since you do not want to install mautic api library as part of existing “bundle” of dependencies, create another folder in mautic install called lib
  • Move to folder lib
  • Create composer.json file and put the following contents in:
{
  "require": {
    "mautic/api-library": "^3.0"
  },
}
  • Now run composer install --no-dev

Api library should be installed inside vendor directory composer created.

Now take the script, I created above, make sure you fix the path to vendor/autoload.php file at the top and edit the rest of the things where you see string “YOURVALUE” and give it a go (I did not test this and might not be the most optimal solution, but you should be able to use api library as documented in github repository here: < GitHub - mautic/api-library: Mautic API Library >).

1 Like