NAV
php json
  • Introduction
  • REST API
  • Webhooks
  • Javascript SDK
  • Introduction

    Welcome to the maatoo API Documentation! This documentation will go over how to integrate applications outside of maatoo using our REST API.

    If you have any questions, feedback or would like to have a virtual coffee break, feel free to reach out to support@maatoo.io.

    REST API

    Mautic provides a REST API to manipulate leads and/or obtain information for various entities of Mautic.

    Error Handling

    If an OAuth error is encountered, it'll be a JSON encoded array similar to:

    {
      "error": "invalid_grant",
      "error_description": "The access token provided has expired."
    }
    

    If a system error encountered, it'll be a JSON encoded array similar to:

    {
        "error": {
            "message": "You do not have access to the requested area/action.",
            "code": 403
        }
    }
    

    Mautic version check

    In case your API service wants to support several Mautic versions with different features, you might need to check the version of Mautic you communicate with. Since Mautic 2.4.0 the version number is added to all API response headers. The header name is Mautic-Version. With Mautic PHP API library you can get the Mautic version like this:

    // Make any API request:
    $api = $this->getContext('contacts');
    $response = $api->getList('', 0, 1);
    
    // Get the version number from the response header:
    $version = $api->getMauticVersion();
    

    $version will be in a semantic versioning format: [major].[minor].[patch]. For example: 2.4.0. If you'll try it on the latest GitHub version, the version will have -dev at the end. Like 2.5.1-dev.

    Authorization

    Mautic uses OAuth or Basic Authentication (as of Mautic 2.3.0) for API authorization. It supports both OAuth 1a and OAuth 2; however, as of 1.1.2, the administrator of the Mautic instance must choose one or the other. Of course OAuth 2 is only recommended for servers secured behind SSL. Basic authentication must be enabled in Configuration -> API Settings.

    The Mautic administrator should enable the API in the Configuration -> API Settings. This will add the "API Credentials" to the admin menu. A client/consumer ID and secret should then be generated which will be used in the following processes.

    All authorization requests should be made to the specific Mautic instances URL, i.e. https://your-mautic.com.

    OAuth 1a

    <?php
    use Mautic\Auth\ApiAuth;
    
    // $initAuth->newAuth() will accept an array of OAuth settings
    $settings = array(
        'baseUrl'      => 'https://your-mautic.com',
        'version'      => 'OAuth1a',
        'clientKey'    => '5ad6fa7asfs8fa7sdfa6sfas5fas6asdf8',
        'clientSecret' => 'adf8asf7sf54asf3as4f5sf6asfasf97dd', 
        'callback'     => 'https://your-callback.com'
    );
    
    // Initiate the auth object
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    
    // Initiate process for obtaining an access token; this will redirect the user to the authorize endpoint and/or set the tokens when the user is redirected back after granting authorization
    
    if ($auth->validateAccessToken()) {
        if ($auth->accessTokenUpdated()) {
            $accessTokenData = $auth->getAccessTokenData();
    
            //store access token data however you want
        }
    }
    

    The OAuth 1a method is recommended for servers that are not behind https. Note that OAuth 1a access tokens do not expire.

    OAuth 1a can be a complicated method due to the need to generate a signature for the request. If anything is off with the signature, the request will not be validated.

    Authorization

    Step One - Obtain a Request Token

    The first step is to obtain a request token that will be used when directing the user to the authorization page.

    Make a POST to the request token endpoint /oauth/v1/request_token:

    POST /oauth/v1/request_token
    Authorization: 
            OAuth oauth_callback="https%3A%2F%2Fyour-callback-uri.com",
                  oauth_consumer_key="CONSUMER_KEY",
                  oauth_nonce="UNIQUE_STRING",
                  oauth_signature="GENERATED_REQUEST_SIGNATURE",
                  oauth_signature_method="HMAC-SHA1",
                  oauth_timestamp="1318467427",
                  oauth_version="1.0"
    

    (note that the header has been wrapped for legibility)

    Review Generating the Authorization Header on the specifics of generating the OAuth header.

    The response will be a query string:

    oauth_token=REQUEST_TOKEN&oauth_token_secret=REQUEST_TOKEN_SECRET&oauth_expires_in=3600
    

    Parse the string and use the parameters in the next step as indicated.

    Note that the refresh token is only good for the number of seconds specified in oauth_expires_in.

    Step Two - Authorization

    Now redirect the user to the authorization endpoint oauth/v1/authorize with the request token as part of the URL's query.

    If the callback is something different than what is configured in Mautic, url encode it and include in the query as oauth_callback.

    /oauth/v1/authorize?oauth_token=REQUEST_TOKEN&oauth_callback=https%3A%2F%2Fyour-callback-uri.com
    

    The user will login and Mautic will redirect back to the either the consumer's configured callback or to the oauth_callback included in the query.

    The callback will include oauth_token and oauth_verifier in the URL's query.

    Compare the oauth_token in the query with that obtained in step two to ensure they are the same and prevent cross-site request forgery.

    oauth_verifier will need to be part of the header generated in step three.

    Step Three - Obtain an Access Token

    Generate the Authorization header and make a POST to the access token endpoint /oauth/v1/access_token.

    When generating the header, the oauth_token_secret returned in step two should be used as the TOKEN_SECRET in the composite key.

    oauth_verifier from step two should be part of the Authorization header generated.

    POST /oauth/v1/access_token
    Authorization: 
            OAuth oauth_callback="https%3A%2F%2Fyour-callback-uri.com",
                  oauth_consumer_key="CONSUMER_KEY",
                  oauth_nonce="UNIQUE_STRING",
                  oauth_signature="GENERATED_REQUEST_SIGNATURE",
                  oauth_signature_method="HMAC-SHA1",
                  oauth_timestamp="1318467427",
                  oauth_verifier="OAUTH_VERIFIER_FROM_STEP_TWO"
                  oauth_version="1.0"
    

    (note that the header has been wrapped for legibility)

    The response should include a query string with the access token:

    oauth_token=ACCESS_TOKEN&oauth_token_secret=ACCESS_TOKEN_SECRET
    

    The oauth_token can be included in the authorize header and the oauth_token_secret should be used as the TOKEN_SECRET in the composite key when signing API requests.

    Generating the Authorization Header

    The OAuth header may include the following parameters:

    Key Description
    oauth_callback Optional, URL encoded callback to redirect the user to after authorization. If the callback URL is set in Mautic, this must match.
    oauth_consumer_key The consumer key obtained from Mautic's API Credentials
    oauth_nonce Uniquely generated string that should be used only once
    oauth_signature Signature generated from all applicable data for the request
    oauth_signature_method Method for creating the signature. Currently, only HMAC-SHA1 is supported.
    oauth_timestamp Current unix timestamp
    oauth_token The access token
    oauth_verifier Returned after authorization and used when requesting an access token
    oauth_version Should always be 1.0
    Step One - Build the Base String

    The base string is used to generate the oauth_signature.

    The structure of the base string is as follows:

    METHOD&URL_ENCODED_URI&NORMALIZED_PARAMETERS
    

    METHOD should be the request method and should always be capitalized.

    URL_ENCODED_URI should be the base URI the request is made to. It should not include any query parameters (query parameters should be part of NORMALIZED_PARAMETERS).

    NORMALIZED_PARAMETERS should be a url encoded, alphabetically sorted query string of the above oauth parameters (except oauth_signature) plus the parameters of the request (query/post body).

    Each key and each value of the parameters must be url encoded individually as well.

    Then each url encoded key/value pair should be concatenated into a single string with an ampersand (&) as the glue character.

    For example, let's say a request includes a query of title=Mr&firstname=Joe&lastname=Smith. The process would look something like the following (replacing urlencode() with whatever function is appropriate for the language being used). Of course realistically, natural sort and loop functions would be used.

    urlencode(
        urlencode(firstname)=urlencode(Joe)
        &urlencode(lastname)=urlencode(smith)
        &urlencode(oauth_callback)=urlencode(https%3A%2F%2Fyour-callback-uri.com)
        &urlencode(oauth_consumer_key)=urlencode(kdjafs7fsdf86ads7a98a87df6ad9fsf98ad7f)
        &urlencode(oauth_nonce)=urlencode(ak877asdf6adf68asd9fas)
        &urlencode(oauth_signature_method)=urlencode(HMAC-SHA1)
        &urlencode(oauth_timestamp)=urlencode(1437604736)
        &urlencode(oauth_version)=urlencode(1.0)
        &urlencode(title)=urlencode(Mr)
    )
    

    Put all together, a base string might look like:

    GET&http%3A%2F%2Fyour-mautic.com%2Fapi&firstname%3DJoe%26lastName%3DSmith%26oauth_callback%3Dhttps%253A%252F%252Fyour-callback-uri.com%26oauth_consumer_key%3Dkdjafs7fsdf86ads7a98a87df6ad9fsf98ad7f%26oauth_nonce%3Dak877asdf6adf68asd9fas%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1437604736%26oauth_version%3D1.0%26title%3DMr
    
    Step Two - Build the Composite Key

    The composite key is used to encrypt the base string. It is composed of the consumer secret and the token secret if available (post authorization) combined with an ampersand (&).

    CLIENT_SECRET&TOKEN_SECRET
    

    If the token secret is not available, i.e. during the request token process, then an ampersand (&) should still be used.

     CLIENT_SECRET&
     

    Step Three - Generate the Signature

    Now, using the base string and the composite key, the signature can be generated using the appropriate HMAC function available to the language used. The signature generated should then be base64 encoded prior to being used in the Authorization header.

     base64_encode(
        hmac_sha1(BASE_STRING, COMPOSITE_KEY)
     )
     

    The resulting string should then be used included in the header as oauth_signature.

    Signing the API Request

    To sign the API request, generate the Authorization header using the obtained access token.

    POST /api/leads/new
    Authorization: 
            OAuth oauth_callback="https%3A%2F%2Fyour-callback-uri.com",
                  oauth_consumer_key="CONSUMER_KEY",
                  oauth_nonce="UNIQUE_STRING",
                  oauth_signature="GENERATED_REQUEST_SIGNATURE",
                  oauth_signature_method="HMAC-SHA1",
                  oauth_timestamp="1318467427",
                  oauth_token="ACCESS_TOKEN"
                  oauth_version="1.0"
                  
    title=Mr&firstname=Joe&lastname=Smith
    

    (note that the header has been wrapped for legibility)

    OAuth 2

    <?php
    use Mautic\Auth\ApiAuth;
    
    // $initAuth->newAuth() will accept an array of OAuth settings
    $settings = array(
        'baseUrl'      => 'https://your-mautic.com',
        'version'      => 'OAuth2',
        'clientKey'    => '5ad6fa7asfs8fa7sdfa6sfas5fas6asdf8',
        'clientSecret' => 'adf8asf7sf54asf3as4f5sf6asfasf97dd', 
        'callback'     => 'https://your-callback.com'
    );
    
    // Initiate the auth object
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    
    // Initiate process for obtaining an access token; this will redirect the user to the authorize endpoint and/or set the tokens when the user is redirected back after granting authorization
    
    if ($auth->validateAccessToken()) {
        if ($auth->accessTokenUpdated()) {
            $accessTokenData = $auth->getAccessTokenData();
    
            //store access token data however you want
        }
    }
    

    Authorization

    Step One - Obtain Authorization Code

    Redirect the user to the authorize endpoint oauth/v2/authorize:

    GET /oauth/v2/authorize?
        client_id=CLIENT_ID
        &grant_type=authorization_code
        &redirect_uri=https%3A%2F%2Fyour-redirect-uri.com%2Fcallback
        &response_type=code
        &state=UNIQUE_STATE_STRING
    

    (note that the query has been wrapped for legibility)

    The user will be prompted to login. Once they do, Mautic will redirect back to the URL specified in redirect_uri with a code appended to the query.

    It may look something like: https://your-redirect-uri.com?code=UNIQUE_CODE_STRING&state=UNIQUE_STATE_STRING

    The state returned should be compared against the original to ensure nothing has been tampered with.

    Step Two - Replace with an Access Token

    Obtain the value of the code from Step One then immediately POST it back to the access token endpoint oauth/v2/token with:

    POST /oauth/v2/token
    
    client_id=CLIENT_ID
        &client_secret=CLIENT_SECRET
        &grant_type=authorization_code
        &redirect_uri=https%3A%2F%2Fyour-redirect-uri.com%2Fcallback
        &code=UNIQUE_CODE_STRING
    

    (note that the post body has been wrapped for legibility)

    The response returned should be a JSON encoded string:

        {
            access_token: "ACCESS_TOKEN",
            expires_in: 3600,
            token_type: "bearer",
            scope: "",
            refresh_token: "REFRESH_TOKEN"
        }
    

    This data should be stored in a secure location and used to authenticate API requests.

    Refresh Tokens

    The response's expires_in is the number of seconds the access token is good for and may differ based on what is configured in Mautic. The code handling the authorization process should generate an expiration timestamp based on that value. For example <?php $expiration = time() + $response['expires_in']; ?>. If the access token has expired, the refresh_token should be used to obtain a new access token.

    By default, the refresh token is valid for 14 days. - If your application requests a new access token using the refresh token within 14 days, no user interaction is needed. Your application gets both a new access token and a new refresh token (which is valid for another 14 days after it's issued); - If your application does not request a new token using the refresh token within 14 days, user interaction is required in order to get new tokens.

    The refresh token's expiration time is configurable through Mautic's Configuration.

    To obtain a new access token, a POST should be made to the access token's endpoint oauth/v2/token using the refresh_token grant type.

    POST /oauth/v2/token
        
    client_id=CLIENT_ID
        &client_secret=CLIENT_SECRET
        &grant_type=refresh_token
        &refresh_token=REFRESH_TOKEN
        &redirect_uri=https%3A%2F%2Fyour-redirect-uri.com%2Fcallback
    

    (note that the post body has been wrapped for legibility)

    The response returned should be a JSON encoded string:

        {
            access_token: "NEW_ACCESS_TOKEN",
            expires_in: 3600,
            token_type: "bearer",
            scope: "",
            refresh_token: "REFRESH_TOKEN"
        }
    

    Authenticating the API Request

    Authenticating the API request with OAuth2 is easy. Choose one of the following methods that is appropriate for the application's needs.

    Authorization Header

    By using an authorization header, any request method can be authenticated.

    However, note that this method requires that the server Mautic is installed on passes headers to PHP or has access to the apache_request_headers() function. apache_request_headers() is not available to PHP running under fcgi.

    Authorization: Bearer ACCESS_TOKEN
    
    Method Specific

    The access token can also be appended to the query or included in the body of a POST.

    GET https://your-mautic.com/api/leads?access_token=ACCESS_TOKEN
    
    POST https://your-mautic.com/api/leads/new
    
    firstname=John&lastname=Smith&access_token=ACCESS_TOKEN
    

    Basic Authentication

    As of Mautic 2.3.0, support for basic authentication can be enabled through Mautic's Configuration -> API Settings. As with OAuth2, it is only recommended to use basic authentication over HTTPS.

    To authorize a request for basic authentication, set an Authorization header.

    1. Combine the username and password of a Mautic user with a colon :. For example, user:password.
    2. Base64 encode the string from above. dXNlcjpwYXNzd29yZA==.
    3. Add an Authorization header to each API request as Authorization: Basic dXNlcjpwYXNzd29yZA==

    Endpoints

    Assets

    Use this endpoint to obtain details on Mautic's assets.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $assetApi = $api->newApi("assets", $auth, $apiUrl);
    
    

    Get Asset

    <?php
    
    //...
    $asset = $assetApi->get($id);
    
    {
        "asset": {
            "id": 1,
            "title": "Product Whitepaper",
            "description": "Some description",
            "alias": "whitepaper",
            "language": "en",
            "isPublished": true,
            "publishUp": "2015-06-07T06:28:27+00:00",
            "publishDown": "2015-06-30T06:28:27+00:00",
            "dateAdded": "2015-06-07T06:28:27+00:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-06-010T09:30:47+00:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "downloadCount": 10,
            "uniqueDownloadCount": 8,
            "revision": 1,
            "category": {
                "createdByUser": "John Doe",
                "modifiedByUser": "John Doe",
                "id": 19,
                "title": "test",
                "alias": "test",
                "description": null,
                "color": null,
                "bundle": "asset"
            },
            "extension": "pdf",
            "mime": "application/pdf",
            "size": 269128,
            "downloadUrl": "https://your-mautic.com/asset/1:whitepaper"
        }
    }
    

    Get an individual asset by ID.

    HTTP Request

    GET /assets/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Asset Properties

    Name Type Description
    id int ID of the asset
    title string Title/name of the asset
    description string/null Description of the asset
    alias string Used to generate the URL for the asset
    language string Locale of the asset
    isPublished bool Published state
    publishUp datetime/null Date/time when the asset should be published
    publishDown datetime/null Date/time the asset should be un published
    dateAdded datetime Date/time asset was created
    createdBy int ID of the user that created the asset
    createdByUser string Name of the user that created the asset
    dateModified datetime/null Date/time asset was last modified
    modifiedBy int ID of the user that last modified the asset
    modifiedByUser string Name of the user that last modified the asset
    downloadCount int Total number of downloads
    uniqueDownloadCount int Unique number of downloads
    revision int Revision version
    category object/null Object with the category details
    extension string Extension of the asset
    mime string Mime type of the asset
    size int Filesize of the asset in bytes
    downloadUrl string Public download URL for the asset

    List Assets

    <?php
    // ...
    
    $assets = $assetApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "assets": [
            {
                "id": 1,
                "title": "Product Whitepaper",
                "description": "Some description",
                "alias": "whitepaper",
                "language": "en",
                "isPublished": true,
                "publishUp": "2015-06-07T06:28:27+00:00",
                "publishDown": "2015-06-30T06:28:27+00:00",
                "dateAdded": "2015-06-07T06:28:27+00:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": "2015-06-010T09:30:47+00:00",
                "modifiedBy": 1,
                "modifiedByUser": "Joe Smith",
                "downloadCount": 10,
                "uniqueDownloadCount": 8,
                "revision": 1,
                "category": null,
                "extension": "pdf",
                "mime": "application/pdf",
                "size": 269128,
                "downloadUrl": "https://your-mautic.com/asset/1:whitepaper"
            }
        ]
    }
    

    HTTP Request

    GET /assets

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Asset.

    Create Asset

    <?php 
    
    /**
     * Local asset example
     */
    // Upload a local file first
    $apiContextFiles = $this->getContext('files');
    $apiContextFiles->setFolder('assets');
    $fileRequest = array(
        'file' => dirname(__DIR__).'/'.'mauticlogo.png'
    );
    $response = $apiContextFiles->create($fileRequest);
    
    $data = array(
        'title' => 'Mautic Logo sent as a API request',
        'storageLocation' => 'local',
        'file' => $response['file']['name']
    );
    
    $asset = $assetApi->create($data);
    
    
    /**
     * Remote asset example
     */
    $data = array(
        'title' => 'PDF sent as a API request',
        'storageLocation' => 'remote',
        'file' => 'https://www.mautic.org/media/logos/logo/Mautic_Logo_DB.pdf'
    );
    
    $asset = $assetApi->create($data);
    
    

    Create a new asset. There are 2 options: local or remote asset.

    HTTP Request

    POST /assets/new

    Post Parameters

    Name Description
    title string
    storageLocation string
    file string

    Response

    Expected Response Code: 201

    Properties

    Same as Get Asset.

    Edit Asset

    <?php
    
    $id   = 1;
    $data = array(
        'type' => 'general',
    );
    
    // Create new a asset of ID 1 is not found?
    $createIfNotFound = true;
    
    $asset = $assetApi->edit($id, $data, $createIfNotFound);
    

    Edit a new asset. Asset that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a asset if the given ID does not exist and clears all the asset information, adds the information from the request. PATCH fails if the asset with the given ID does not exist and updates the asset field values with the values form the request.

    HTTP Request

    To edit a asset and return a 404 if the asset is not found:

    PATCH /assets/ID/edit

    To edit a asset and create a new one if the asset is not found:

    PUT /assets/ID/edit

    Post Parameters

    Name Description
    title string
    storageLocation string
    file string

    Response

    If PUT, the expected response code is 200 if the asset was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Asset.

    Delete Asset

    <?php
    
    $asset = $assetApi->delete($id);
    

    Delete a asset. In case of local storage location, the local file will be deleted as well.

    HTTP Request

    DELETE /assets/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Asset.

    Campaigns

    Use this endpoint to obtain details on Mautic's campaigns.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth    = new ApiAuth();
    $auth        = $initAuth->newAuth($settings);
    $apiUrl      = "https://your-mautic.com";
    $api         = new MauticApi();
    $campaignApi = $api->newApi("campaigns", $auth, $apiUrl);
    

    Get Campaign

    <?php
    
    //...
    $campaign = $campaignApi->get($id);
    
    {
        "campaign": {
            "id": 3,
            "name": "Email A/B Test",
            "description": null,
            "isPublished": true,
            "publishUp": null,
            "publishDown": null,
            "dateAdded": "2015-07-15T15:06:02-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-20T13:11:56-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "category": null,
            "events": {
                "28": {
                    "id": 28,
                    "type": "lead.changepoints",
                    "eventType": "action",
                    "name": "Adjust lead points",
                    "description": null,
                    "order": 1,
                    "properties": {
                      "points": 20
                    },
                    "triggerDate": null,
                    "triggerInterval": 1,
                    "triggerIntervalUnit": "d",
                    "triggerMode": "immediate",
                    "children": [],
                    "parent": null,
                    "decisionPath": null
                }
            }
        }
    }
    

    Get an individual campaign by ID.

    HTTP Request

    GET /campaigns/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Campaign Properties

    Name Type Description
    id int ID of the campaign
    name string Name of the campaign
    description string/null Description of the campaign
    alias string Used to generate the URL for the campaign
    isPublished bool Published state
    publishUp datetime/null Date/time when the campaign should be published
    publishDown datetime/null Date/time the campaign should be un published
    dateAdded datetime Date/time campaign was created
    createdBy int ID of the user that created the campaign
    createdByUser string Name of the user that created the campaign
    dateModified datetime/null Date/time campaign was last modified
    modifiedBy int ID of the user that last modified the campaign
    modifiedByUser string Name of the user that last modified the campaign
    events array Array of Event entities for the campaign. See below.

    Event Properties

    Name Type Description
    id int ID of the event
    name string Name of the event
    description string Optional description for the event
    type string Type of event
    eventType string "action" or "decision"
    order int Order in relation to the other events (used for levels)
    properties object Configured properties for the event
    triggerMode string "immediate", "interval" or "date"
    triggerDate datetime/null Date/time of when the event should trigger if triggerMode is "date"
    triggerInterval int/null Interval for when the event should trigger
    triggerIntervalUnit string Interval unit for when the event should trigger. Options are i = minutes, h = hours, d = days, m = months, y = years
    children array Array of this event's children ,
    parent object/null This event's parent
    decisionPath string/null If the event is connected into an action, this will be "no" for the non-decision path or "yes" for the actively followed path.

    List Campaigns

    <?php
    // ...
    
    $campaigns = $campaignApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "campaigns": {
            "3": {
                "id": 3,
                "name": "Welcome Campaign",
                "description": null,
                "isPublished": true,
                "publishUp": null,
                "publishDown": null,
                "dateAdded": "2015-07-15T15:06:02-05:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": "2015-07-20T13:11:56-05:00",
                "modifiedBy": 1,
                "modifiedByUser": "Joe Smith",
                "category": null,
                "events": {
                    "22": {
                        "id": 22,
                        "type": "email.send",
                        "eventType": "action",
                        "name": "Send welcome email",
                        "description": null,
                        "order": 1,
                        "properties": {
                            "email": 1
                        },
                        "triggerMode": "immediate",
                        "triggerDate": null,
                        "triggerInterval": null,
                        "triggerIntervalUnit": null,
                        "children": [],
                        "parent": null,
                        "decisionPath": null
                    },
                    "28": {
                        "id": 28,
                        "type": "lead.changepoints",
                        "eventType": "action",
                        "name": "Adjust lead points",
                        "description": null,
                        "order": 2,
                        "properties": {
                            "points": 20
                        },
                        "triggerMode": "immediate",                
                        "triggerDate": null,
                        "triggerInterval": null,
                        "triggerIntervalUnit": null,
                        "children": [],
                        "parent": null,
                        "decisionPath": null
                    }
                }
            }
        }
    }
    

    HTTP Request

    GET /campaigns

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    published Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Campaign.

    List Campaign Contacts

    This endpoint is basically an alias for the stats endpoint with 'campaign_leads' table and campaign_id specified. Other parameters are the same as in the stats endpoint.

    <?php
    // ...
    
    $response = $campaignApi->getContacts($campaignId, $start, $limit, $order, $where);
    
    {  
      "total":"1",
      "contacts":[  
        {  
          "campaign_id":"311",
          "lead_id":"3126",
          "date_added":"2017-01-25 15:11:10",
          "manually_removed":"0",
          "manually_added":"1"
        }
      ]
    }
    

    HTTP Request

    GET /campaigns/ID/contacts

    Query Parameters

    Response

    Expected Response Code: 200

    See JSON code example.

    Create Campaign

    <?php
    
    $data = array(
        'name'        => 'Campaign A',
        'description' => 'This is my first campaign created via API.',
        'isPublished' => 1
    );
    
    $campaign = $campaignApi->create($data);
    

    Create a new campaign. To see more advanced example with campaing events and so on, see the unit tests.

    HTTP Request

    POST /campaigns/new

    Post Parameters

    Name Description
    name Campaign name is the only required field
    alias string
    description A description of the campaign.
    isPublished A value of 0 or 1

    Response

    Expected Response Code: 201

    Properties

    Same as Get Campaign.

    Clone A Campaign

    <?php
    
    $camnpaignId = 12;
    
    $campaign = $campaignApi->cloneCampaign($campaignId);
    

    Clone an existing campaign. To see more advanced example with campaign events and so on, see the unit tests.

    HTTP Request

    POST /campaigns/clone/CAMPAIGN_ID

    Response

    Expected Response Code: 201

    Properties

    Same as Get Campaign.

    Edit Campaign

    <?php
    
    $id   = 1;
    $data = array(
        'name'        => 'New campaign name',
        'isPublished' => 0
    );
    
    // Create new a campaign of ID 1 is not found?
    $createIfNotFound = true;
    
    $campaign = $campaignApi->edit($id, $data, $createIfNotFound);
    

    Edit a new campaign. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a campaign if the given ID does not exist and clears all the campaign information, adds the information from the request. PATCH fails if the campaign with the given ID does not exist and updates the campaign field values with the values form the request.

    HTTP Request

    To edit a campaign and return a 404 if the campaign is not found:

    PATCH /campaigns/ID/edit

    To edit a campaign and create a new one if the campaign is not found:

    PUT /campaigns/ID/edit

    Post Parameters

    Name Description
    name Campaign name is the only required field
    alias Name alias generated automatically if not set
    description A description of the campaign.
    isPublished A value of 0 or 1

    Response

    If PUT, the expected response code is 200 if the campaign was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Campaign.

    Delete Campaign

    <?php
    
    $campaign = $campaignApi->delete($id);
    

    Delete a campaign.

    HTTP Request

    DELETE /campaigns/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Campaign.

    Add Contact to a Campaign

    <?php
    
    //...
    $response = $campaignApi->addContact($campaignId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually add a contact to a specific campaign.

    HTTP Request

    POST /campaigns/CAMPAIGN_ID/contact/CONTACT_ID/add

    Response

    Expected Response Code: 200

    See JSON code example.

    Remove Contact from a Campaign

    <?php
    
    //...
    $response = $listApi->removeContact($campaignId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually remove a contact from a specific campaign.

    HTTP Request

    POST /campaigns/CAMPAIGN_ID/contact/CONTACT_ID/remove

    Response

    Expected Response Code: 200

    See JSON code example.

    Categories

    Use this endpoint to obtain details on Mautic's categories or to manipulate category memberships.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth    = new ApiAuth();
    $auth        = $initAuth->newAuth($settings);
    $apiUrl      = "https://your-mautic.com";
    $api         = new MauticApi();
    $categoryApi = $api->newApi("categories", $auth, $apiUrl);
    

    Get Category

    <?php
    
    //...
    $category = $categoryApi->get($id);
    
    {  
      "category":{  
        "id":221,
        "title":"test",
        "alias":"test4",
        "description":null,
        "color":null,
        "bundle":"asset"
      }
    }
    

    Get an individual category by ID.

    HTTP Request

    GET /categories/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Category Properties

    Name Type Description
    id int ID of the category
    isPublished boolean Whether the category is published
    dateAdded datetime Date/time category was created
    createdBy int ID of the user that created the category
    createdByUser string Name of the user that created the category
    dateModified datetime/null Date/time category was last modified
    modifiedBy int ID of the user that last modified the category
    modifiedByUser string Name of the user that last modified the category
    title string The category title
    alias string The category alias
    description string The category description
    color string The category color
    bundle string The bundle where the category will be available

    List Contact Categories

    <?php
    
    //...
    $categories = $categoryApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
      "total":8,
      "categories":[  
        {  
          "id":1,
          "title":"Bold",
          "alias":"bold",
          "description":null,
          "color":"b36262",
          "bundle":"point"
        },
        [...]
      ]
    }
    

    Returns a list of contact categories available to the user. This list is not filterable.

    HTTP Request

    GET /categories

    Response

    Expected Response Code: 200

    See JSON code example.

    Category Properties

    Name Type Description
    id int ID of the category
    isPublished boolean Whether the category is published
    dateAdded datetime Date/time category was created
    createdBy int ID of the user that created the category
    createdByUser string Name of the user that created the category
    dateModified datetime/null Date/time category was last modified
    modifiedBy int ID of the user that last modified the category
    modifiedByUser string Name of the user that last modified the category
    title string The category title
    alias string The category alias
    description string The category description
    color string The category color
    bundle string The bundle where the category will be available

    Create Category

    <?php 
    
    $data = array(
        'categoryname' => 'test',
        'categoryemail' => 'test@category.com',
        'categorycity' => 'Raleigh',
    );
    
    $category = $categoryApi->create($data);
    

    Create a new category.

    HTTP Request

    POST /categories/new

    Post Parameters

    Name Description
    title string
    bundle string

    Response

    Expected Response Code: 201

    Properties

    Same as Get Category.

    Edit Category

    <?php
    
    $id   = 1;
    $data = array(
        'title' => 'test',
        'bundle' => 'asset'
    );
    
    // Create new a category of ID 1 is not found?
    $createIfNotFound = true;
    
    $category = $categoryApi->edit($id, $data, $createIfNotFound);
    

    Edit a new category. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a category if the given ID does not exist and clears all the category information, adds the information from the request. PATCH fails if the category with the given ID does not exist and updates the category field values with the values form the request.

    HTTP Request

    To edit a category and return a 404 if the category is not found:

    PATCH /categories/ID/edit

    To edit a category and create a new one if the category is not found:

    PUT /categories/ID/edit

    Post Parameters

    Name Description
    title string
    bundle string

    Response

    If PUT, the expected response code is 200 if the category was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Category.

    Delete Category

    <?php
    
    $category = $categoryApi->delete($id);
    

    Delete a category.

    HTTP Request

    DELETE /categories/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Category.

    Assign a Category

    To assign a category to an entity simply set category = [ID] to the payload. For example this is how a category 123 can be asssigned to a new Asset:

    $data = array(
        'title' => 'PDF sent as a API request',
        'storageLocation' => 'remote',
        'file' => 'https://www.mautic.org/media/logos/logo/Mautic_Logo_DB.pdf'
        'category' => 123
    );
    
    $asset = $assetApi->create($data);
    

    The category must exist in the Mautic instance and the entity must support categories,

    Companies

    Use this endpoint to obtain details on Mautic's companies or to manipulate contact-company memberships.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth   = new ApiAuth();
    $auth       = $initAuth->newAuth($settings);
    $apiUrl     = "https://your-mautic.com";
    $api        = new MauticApi();
    $companyApi = $api->newApi("companies", $auth, $apiUrl);
    

    Get Company

    <?php
    
    //...
    $company = $companyApi->get($id);
    
    {  
        "company":{  
            "isPublished":true,
            "dateAdded":"2016-10-25T09:46:36+00:00",
            "createdBy":1,
            "createdByUser":"John Doe",
            "dateModified":null,
            "modifiedBy":null,
            "modifiedByUser":null,
            "id":176,
            "fields":{  
                "core":{  
                    "companywebsite":{  
                        "id":"91",
                        "label":"Website",
                        "alias":"companywebsite",
                        "type":"url",
                        "group":"core",
                        "field_order":"8",
                        "object":"company",
                        "value":null
                    },
                    [...]
                },
                "professional":{  
                    "companyannual_revenue":{  
                        "id":"90",
                        "label":"Annual Revenue",
                        "alias":"companyannual_revenue",
                        "type":"number",
                        "group":"professional",
                        "field_order":"10",
                        "object":"company",
                        "value":null
                    },
                    [...]
                },
                "other":[],
                "all":{  
                    "companywebsite":null,
                    "companycountry":null,
                    "companyzipcode":null,
                    "companystate":null,
                    "companycity":"Raleigh",
                    "companyphone":null,
                    "companyemail":"test@company.com",
                    "companyaddress2":null,
                    "companyaddress1":null,
                    "companyname":"test",
                    "companyannual_revenue":null,
                    "companyfax":null,
                    "companynumber_of_employees":null,
                    "companydescription":null
                }
            }
        }
    }
    

    Get an individual company by ID.

    HTTP Request

    GET /companies/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Company Properties

    Name Type Description
    id int ID of the company
    isPublished boolean Whether the company is published
    dateAdded datetime Date/time company was created
    createdBy int ID of the user that created the company
    createdByUser string Name of the user that created the company
    dateModified datetime/null Date/time company was last modified
    modifiedBy int ID of the user that last modified the company
    modifiedByUser string Name of the user that last modified the company
    fields array Custom fields for the company

    List Contact Companies

    <?php
    
    //...
    $companies = $companyApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
      "total": 13,
      "companies": {
        "176": {  
          "isPublished":true,
          "dateAdded":"2016-10-25T09:46:36+00:00",
          "createdBy":1,
          "createdByUser":"John Doe",
          "dateModified":null,
          "modifiedBy":null,
          "modifiedByUser":null,
          "id":176,
          "fields":{  
            "core":{  
                "companywebsite":{  
                    "id":"91",
                    "label":"Website",
                    "alias":"companywebsite",
                    "type":"url",
                    "group":"core",
                    "field_order":"8",
                    "object":"company",
                    "value":null
                },
                [...]
            },
            "professional":{  
                "companyannual_revenue":{  
                    "id":"90",
                    "label":"Annual Revenue",
                    "alias":"companyannual_revenue",
                    "type":"number",
                    "group":"professional",
                    "field_order":"10",
                    "object":"company",
                    "value":null
                },
                [...]
            },
            "other":[],
            "all":{  
                "companywebsite":null,
                "companycountry":null,
                "companyzipcode":null,
                "companystate":null,
                "companycity":"Raleigh",
                "companyphone":null,
                "companyemail":"test@company.com",
                "companyaddress2":null,
                "companyaddress1":null,
                "companyname":"test",
                "companyannual_revenue":null,
                "companyfax":null,
                "companynumber_of_employees":null,
                "companydescription":null
            }
        }
      },
      [...]
      }
    }
    

    Returns a list of contact companies available to the user. This list is not filterable.

    HTTP Request

    GET /companies

    ** Query Parameters **

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.

    Response

    Expected Response Code: 200

    See JSON code example.

    Company Properties

    Name Type Description
    id int ID of the company
    isPublished boolean Whether the company is published
    dateAdded datetime Date/time company was created
    createdBy int ID of the user that created the company
    createdByUser string Name of the user that created the company
    dateModified datetime/null Date/time company was last modified
    modifiedBy int ID of the user that last modified the company
    modifiedByUser string Name of the user that last modified the company
    fields array Custom fields for the company

    Create Company

    <?php
    
    $data = array(
        'companyname' => 'test',
        'companyemail' => 'test@company.com',
        'companycity' => 'Raleigh',
        'overwriteWithBlank' => true
    );
    
    $company = $companyApi->create($data);
    

    Create a new company.

    HTTP Request

    POST /companies/new

    Post Parameters

    Name Description
    companyname Company name is the only required field. Other company fields can be sent with a value
    isPublished A value of 0 or 1
    overwriteWithBlank If true, then empty values are set to fields. Otherwise empty values are skipped

    Response

    Expected Response Code: 201

    Properties

    Same as Get Company.

    Edit Company

    <?php
    
    $id   = 1;
    $data = array(
        'companyname' => 'test',
        'companyemail' => 'test@company.com',
        'companycity' => 'Raleigh',
    );
    
    // Create new a company of ID 1 is not found?
    $createIfNotFound = true;
    
    $company = $companyApi->edit($id, $data, $createIfNotFound);
    

    Edit a new company. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a company if the given ID does not exist and clears all the company information, adds the information from the request. PATCH fails if the company with the given ID does not exist and updates the company field values with the values form the request.

    HTTP Request

    To edit a company and return a 404 if the company is not found:

    PATCH /companies/ID/edit

    To edit a company and create a new one if the company is not found:

    PUT /companies/ID/edit

    Post Parameters

    Name Description
    companyname Company name is the only required field. Other company fields can be sent with a value
    isPublished A value of 0 or 1
    overwriteWithBlank If true, then empty values are set to fields. Otherwise empty values are skipped

    Response

    If PUT, the expected response code is 200 if the company was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Company.

    Delete Company

    <?php
    
    $company = $companyApi->delete($id);
    

    Delete a company.

    HTTP Request

    DELETE /companies/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Company.

    Add Contact to a Company

    <?php
    
    //...
    $response = $companyApi->addContact($companyId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually add a contact to a specific company.

    HTTP Request

    POST /companies/COMPANY_ID/contact/CONTACT_ID/add

    Response

    Expected Response Code: 200

    See JSON code example.

    Remove Contact from a Company

    <?php
    
    //...
    $response = $companyApi->removeContact($contactId, $companyId);
    if (empty($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually remove a contact to a specific company.

    HTTP Request

    POST /companies/COMPANY_ID/contact/CONTACT_ID/remove

    Response

    Expected Response Code: 200

    See JSON code example.

    Contacts

    Use this endpoint to manipulate and obtain details on Mautic's contacts.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth   = new ApiAuth();
    $auth       = $initAuth->newAuth($settings);
    $apiUrl     = "https://your-mautic.com";
    $api        = new MauticApi();
    $contactApi = $api->newApi("contacts", $auth, $apiUrl);
    

    Get Contact

    <?php
    
    //...
    $contact = $contactApi->get($id);
    
        "contact": {
            "id": 47,
            "dateAdded": "2015-07-21T12:27:12-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-21T14:12:03-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "owner": {
                "id": 1,
                "username": "joesmith",
                "firstName": "Joe",
                "lastName": "Smith"
            },
            "points": 10,
            "lastActive": "2015-07-21T14:19:37-05:00",
            "dateIdentified": "2015-07-21T12:27:12-05:00",
            "color": "ab5959",
            "ipAddresses": {
                "111.111.111.111": {
                    "ipAddress": "111.111.111.111",
                    "ipDetails": {
                        "city": "",
                        "region": "",
                        "country": "",
                        "latitude": "",
                        "longitude": "",
                        "isp": "",
                        "organization": "",
                        "timezone": ""
                    }
                }
            },
            "fields": {
                "core": {
                    "title": {
                        "id": "1",
                        "label": "Title",
                        "alias": "title",
                        "type": "lookup",
                        "group": "core",
                        "value": "Mr"
                    },
                    "firstname": {
                        "id": "2",
                        "label": "First Name",
                        "alias": "firstname",
                        "type": "text",
                        "group": "core",
                        "value": "Jim"
                    },
    
                    "...": {
                        "..." : "..."
                    }
    
                },
                "social": {
                    "twitter": {
                        "id": "17",
                        "label": "Twitter",
                        "alias": "twitter",
                        "type": "text",
                        "group": "social",
                        "value": "jimcontact"
                    },
    
                    "...": {
                        "..." : "..."
                    }
    
                },
                "personal": [],
                "professional": [],
                "all": {
                    "title": "Mr",
                    "firstname": "Jim",
                    "twitter": "jimcontact",
    
                    "...": "..."
                }
            }
        }
    

    Get an individual contact by ID.

    HTTP Request

    GET /contacts/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    ** Contact Properties **

    Name Type Description
    id int ID of the contact
    isPublished Boolean True if the contact is published
    dateAdded datetime Date/time contact was created
    createdBy int ID of the user that created the contact
    createdByUser string Name of the user that created the contact
    dateModified datetime/null Date/time contact was last modified
    modifiedBy int ID of the user that last modified the contact
    modifiedByUser string Name of the user that last modified the contact
    owner object User object that owns the contact.
    points int Contact's current number of points
    lastActive datetime/null Date/time for when the contact was last recorded as active
    dateIdentified datetime/null Date/time when the contact identified themselves
    color string Hex value given to contact from Point Trigger definitions based on the number of points the contact has been awarded
    ipAddresses array Array of IPs currently associated with this contact
    fields array Array of all contact fields with data grouped by field group. See JSON code example for format. This array includes an "all" key that includes an single level array of fieldAlias => contactValue pairs.
    tags array Array of tags associated with this contact. See JSON code example for format.
    utmtags array Array of UTM Tags associated with this contact. See JSON code example for format.
    doNotContact array Array of Do Not Contact objects. See JSON code example for format.

    List Contacts

    <?php
    
    //...
    $contacts = $contactApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": "1",
        "contacts": {
            "47": {
                "id": 47,
                "isPublished": true,
                "dateAdded": "2015-07-21T12:27:12-05:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": "2015-07-21T14:12:03-05:00",
                "modifiedBy": 1,
                "modifiedByUser": "Joe Smith",
                "owner": {
                    "id": 1,
                    "username": "joesmith",
                    "firstName": "Joe",
                    "lastName": "Smith"
                },
                "points": 10,
                "lastActive": "2015-07-21T14:19:37-05:00",
                "dateIdentified": "2015-07-21T12:27:12-05:00",
                "color": "ab5959",
                "ipAddresses": {
                    "111.111.111.111": {
                        "ipAddress": "111.111.111.111",
                        "ipDetails": {
                            "city": "",
                            "region": "",
                            "country": "",
                            "latitude": "",
                            "longitude": "",
                            "isp": "",
                            "organization": "",
                            "timezone": ""
                        }
                    }
                },
                "fields": {
                    "core": {
                        "title": {
                            "id": "1",
                            "label": "Title",
                            "alias": "title",
                            "type": "lookup",
                            "group": "core",
                            "value": "Mr"
                        },
                        "firstname": {
                            "id": "2",
                            "label": "First Name",
                            "alias": "firstname",
                            "type": "text",
                            "group": "core",
                            "value": "Jim"
                        },
    
                        "...": {
                            "..." : "..."
                        }
                    },
                    "social": {
                        "twitter": {
                            "id": "17",
                            "label": "Twitter",
                            "alias": "twitter",
                            "type": "text",
                            "group": "social",
                            "value": "jimcontact"
                        },
    
                        "...": {
                            "..." : "..."
                        }
                    },
                    "personal": [],
                    "professional": [],
                    "all": {
                        "title": "Mr",
                        "firstname": "Jim",
                        "twitter": "jimcontact",
    
                        "...": "..."
                    }
                },
                "tags": [{
                  "tag": "aTag"
                },
                {
                  "tag": "bTag"
                }],
                "utmtags" : [{
                  "id": 1,
                  "query": {
                    "page": "asd",
                    "cid": "fb1"
                  },
                  "referer": "https://example.com/",
                  "remoteHost": "example.com",
                  "userAgent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0",
                  "utmCampaign": "abcampaign",
                  "utmContent": "page",
                  "utmMedium": "social",
                  "utmSource": "fb",
                  "utmTerm": "test1"
                }],
                "doNotContact": [{
                    "id": 2,
                    "reason": 2,
                    "comments": "",
                    "channel": "email",
                    "channelId": null
                }]
            }
        }
    }
    

    Get a list of contacts.

    HTTP Request

    GET /contacts

    ** Query Parameters **

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response. However, all properties in the response that are written in camelCase need to be changed a bit. Before every capital add an underscore _ and then change the capital letters to non-capital letters. So dateIdentified becomes date_identified, modifiedByUser becomes modified_by_user etc.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.
    where An array of advanced where conditions
    order An array of advanced order statements

    Advanced filtering

    In some cases you may want to filter by specific value(s). Use URL params like this:

    In PHP: php $where = [ [ 'col' => 'phone', 'expr' => 'in', 'val' => '444444444,888888888', ] ]; This design allows to add multiple conditions in the same request.

    If you are not using PHP, here is URL-encoded example of the above where array: GET https://[your_mauitc_domain]/api/contacts?where%5B0%5D%5Bcol%5D=phone&where%5B0%5D%5Bexpr%5D=in&where%5B0%5D%5Bval%5D=444444444,888888888

    List of available expressions

    Response

    Expected Response Code: 200

    See JSON code example.

    ** Properties **

    Same as Get Contact.

    Create Contact

    <?php
    
    $data = array(
        'firstname' => 'Jim',
        'lastname'  => 'Contact',
        'email'     => 'jim@his-site.com',
        'ipAddress' => $_SERVER['REMOTE_ADDR'],
        'overwriteWithBlank' => true,
    );
    
    $contact = $contactApi->create($data);
    

    Create a new contact.

    HTTP Request

    POST /contacts/new

    ** Post Parameters **

    Name Description
    * Any contact field alias can be posted as a parameter. For example, firstname, lastname, email, etc.
    ipAddress IP address to associate with the contact
    lastActive Date/time in UTC; preferablly in the format of Y-m-d H:m:i but if that format fails, the string will be sent through PHP's strtotime then formatted
    owner ID of a Mautic user to assign this contact to
    overwriteWithBlank If true, then empty values are set to fields. Otherwise empty values are skipped

    Response

    Expected Response Code: 201

    ** Properties **

    Same as Get Contact.

    Edit Contact

    <?php
    
    $id   = 1;
    $data = array(
        'email'     => 'jim-new-address@his-site.com',
        'ipAddress' => $_SERVER['REMOTE_ADDR'],    
    );
    
    // Create new a contact of ID 1 is not found?
    $createIfNotFound = true;
    
    $contact = $contactApi->edit($id, $data, $createIfNotFound);
    

    Edit a new contact. Note that this supports PUT or PATCH depending on the desired behavior.

    ** PUT ** creates a contact if the given ID does not exist and clears all the contact information, adds the information from the request. PATCH fails if the contact with the given ID does not exist and updates the contact field values with the values form the request.

    HTTP Request

    To edit a contact and return a 404 if the contact is not found:

    PATCH /contacts/ID/edit

    To edit a contact and create a new one if the contact is not found:

    PUT /contacts/ID/edit

    ** Post Parameters **

    Name Description
    * Any contact field alias can be posted as a parameter. For example, firstname, lastname, email, etc.
    ipAddress IP address to associate with the contact
    lastActive Date/time in UTC; preferably in the format of Y-m-d H:m:i but if that format fails, the string will be sent through PHP's strtotime then formatted
    owner ID of a Mautic user to assign this contact to
    overwriteWithBlank If true, then empty values are set to fields. Otherwise empty values are skipped

    Response

    If PUT, the expected response code is 200 if the contact was edited or 201 if created.

    If PATCH, the expected response code is 200.

    ** Properties **

    Same as Get Contact.

    Note: In order to remove tag from contact add minus - before it. For example: tags: ['one', '-two'] - sending this in request body will add tag one and remove tag two from contact.

    Delete Contact

    <?php
    
    $contact = $contactApi->delete($id);
    

    Delete a contact.

    HTTP Request

    DELETE /contacts/ID/delete

    Response

    Expected Response Code: 200

    ** Properties **

    Same as Get Contact.

    Add Do Not Contact

    <?php
    
    $contactApi->addDnc($contactId, $channel, $reason, $channelId, $comments);
    
    {
      "channelId": "26",
      "reason": "Integration issued DNC",
      "comments": "Unsubscribed via API"
    }
    

    Add a contact to DNC list

    HTTP Request

    To add Do Not Contact entry to a contact:

    POST /contacts/ID/dnc/CHANNEL/add

    Data Parameters (optional)

    Name Description
    channel Channel of DNC. For example 'email', 'sms'... Default is email.
    reason Int value of the reason. Use Contacts constants: Contacts::UNSUBSCRIBED (1), Contacts::BOUNCED (2), Contacts::MANUAL (3). Default is Manual
    channelId ID of the entity which was the reason for unsubscription
    comments A text describing details of DNC entry

    Response

    Same as Get Contact.

    Remove from Do Not Contact

    <?php
    $contactApi->removeDnc($contactId, $channel);
    

    Remove a contact from DNC list

    HTTP Request

    To remove Do Not Contact entry from a contact:

    POST /contacts/ID/dnc/CHANNEL/remove

    Data Parameters (optional)

    Name Description
    channel Channel of DNC. For example 'email', 'sms'... Default is email.

    Response

    Same as Get Contact.

    Add UTM Tags

    <?php
    
    $data = array(
        'utm_campaign' => 'apicampaign',
        'utm_source'   => 'fb',
        'utm_medium'   => 'social',
        'utm_content'  => 'fbad',
        'utm_term'     => 'mautic api',
        'useragent'    => 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0',
        'url'          => '/product/fbad01/',
        'referer'      => 'https://google.com/q=mautic+api',
        'query'        => ['cid'=>'abc','cond'=>'new'], // or as string with "cid=abc&cond=new"
        'remotehost'   => 'example.com',
        'lastActive'   => '2017-01-17T00:30:08+00:00'
     );
    $contactApi->addUtm($contactId, $data);
    

    Add UTM tags to a contact

    HTTP Request

    To add UTM tag entry to a contact:

    POST /contacts/ID/utm/add

    UTM Parameters (required)

    While the parameter array is required, each utm tag entry is optional.

    Name Description
    utm_campaign The UTM Campaign parameter
    utm_source The UTM Source parameter
    utm_medium The UTM Medium parameter
    utm_content The UTM Content parameter
    utm_term The UTM Term parameter
    useragent The browsers UserAgent. If provided a new Device entry will be created if necessary.
    url The page url
    referer The URL of the referer,
    query Any extra query parameters you wish to include. Array or http query string
    remotehost The Host name
    lastActive The date that the action occured. Contacts lastActive date will be updated if included. Date format required 2017-01-17T00:30:08+00:00.

    Response

    Same as Get Contact with the added UTM Tags.

    Remove UTM Tags from a contact

    <?php
    $contactApi->removeUtm($contactId, $utmId);
    

    Remove a set of UTM Tags from a contact

    HTTP Request

    To remove UTM Tags from a contact:

    POST /contacts/ID/utm/UTMID/remove

    Data Parameters

    None required.

    Response

    Same as Get Contact without the removed UTM Tags.

    Add Points

    <?php
    
    $data = array(
         'eventName' => 'Score via api',
         'actionName' => 'Adding',
     );
    $contactApi->addPoints($contactId, $pointDelta, $data);
    

    Add contact points

    HTTP Request

    To add points to a contact and return a 404 if the lead is not found:

    POST /contacts/ID/points/plus/POINTS

    Data Parameters (optional)

    Name Description
    eventName Name of the event
    actionName Name of the action

    Response

    Expected Response Code: 200 json { "success": true }

    Subtract Points

    <?php
    
    $data = array(
         'eventname' => 'Score via api',
         'actionname' => 'Subtracting',
     );
    $contactApi->subtractPoints($contactId, $pointDelta, $data);
    

    Subtract contact points

    HTTP Request

    To subtract points from a contact and return a 404 if the contact is not found:

    POST /contacts/ID/points/minus/POINTS

    Data Parameters (optional)

    Name Description
    eventname Name of the event
    actionname Name of the action

    Response

    Expected Response Code: 200 json { "success": true }

    List Available Owners

    <?php
    
    $owners = $contactApi->getOwners();
    
    [
      {
        "id": 1,
        "firstName": "Joe",
        "lastName": "Smith"
      },
      {
        "id": 2,
        "firstName": "Jane",
        "lastName": "Smith"
      }
    ]
    

    Get a list of owners that can be used to assign contacts to when creating/editing.

    HTTP Request

    GET /contacts/list/owners

    Response

    Expected Response Code: 200

    ** Owner Properties **

    Name Type Description
    id int ID of the Mautic user
    firstName string First name of the Mautic user
    lastName string Last name of the Mautic user

    List Available Fields

    <?php
    
    $fields = $contactApi->getFieldList();
    
    {
        "1": {
            "id": 1,
            "label": "Title",
            "alias": "title",
            "type": "lookup",
            "group": "core",
            "order": 1
        },
        "2": {
            "id": 2,
            "label": "First Name",
            "alias": "firstname",
            "type": "text",
            "group": "core",
            "order": 2
        },
        "3": {
            "id": 3,
            "label": "Last Name",
            "alias": "lastname",
            "type": "text",
            "group": "core",
            "order": 3
        },
    
        "...": {
            "..." : "..."
        }
    }
    

    Get a list of available contact fields including custom ones.

    HTTP Request

    GET /contacts/list/fields

    Response

    Expected Response Code: 200

    ** Field Properties **

    Name Type Description
    id int ID of the field
    label string Field label
    alias string Field alias used as the column name in the database
    type string Type of field. I.e. text, lookup, etc
    group string Group the field belongs to
    order int Field order

    List Contact Notes

    <?php
    
    $notes = $contactApi->getContactNotes($id, $searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "notes": [
            {
                  "id": 1,
                  "text": "<p>Jim is super cool!</p>",
                  "type": "general",
                  "dateTime": "2015-07-23T13:14:00-05:00"
            }
        ]
    }
    

    Get a list of notes for a specific contact.

    HTTP Request

    GET /contacts/ID/notes

    ** Query Parameters **

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.

    Response

    Expected response code: 200

    ** Note Properties **

    Name Type Description
    id int ID of the note
    text string Body of the note
    type string Type of note. Options are "general", "email", "call", "meeting"
    dateTime datetime Date/time string of when the note was created.

    Get Segment Memberships

    <?php
    
    $segments = $contactApi->getContactSegments($id);
    
    {
        "total": 1,
        "segments": {
            "3": {
                "id": 3,
                "name": "New Contacts",
                "alias": "newcontacts"
            }
        }
    }
    

    Get a list of contact segments the contact is a member of.

    HTTP Request

    GET /contacts/ID/segments

    Response

    Expected response code: 200

    ** List Properties **

    Name Type Description
    id int ID of the list
    name string Name of the list
    alias string Alias of the list used with search commands.
    dateAdded datetime Date/time string for when the contact was added to the list
    manuallyAdded bool True if the contact was manually added to the list versus being added by a filter
    manuallyRemoved bool True if the contact was manually removed from the list even though the list's filter is a match

    Change List Memberships

    See Segements.

    Get Campaign Memberships

    <?php
    
    $campaigns = $contactApi->getContactCampaigns($id);
    
    {
        "total": 1,
        "campaigns": {
            "1": {
                "id": 1,
                "name": "Welcome Campaign",
                "dateAdded": "2015-07-21T14:11:47-05:00",
                "manuallyRemoved": false,
                "manuallyAdded": false,
                "list_membership": [
                    3
                ]
            }
        }
    }
    

    Get a list of campaigns the contact is a member of.

    HTTP Request

    GET /contacts/ID/campaigns

    Response

    Expected response code: 200

    ** List Properties **

    Name Type Description
    id int ID of the campaign
    name string Name of the campaign
    dateAdded datetime Date/time string for when the contact was added to the campaign
    manuallyAdded bool True if the contact was manually added to the campaign versus being added by a contact list
    manuallyRemoved bool True if the contact was manually removed from the campaign when the contact's list is assigned to the campaign
    listMembership array Array of contact list IDs this contact belongs to that is also associated with this campaign

    Change Campaign Memberships

    See Campaigns.

    Get Contact's Events

    <?php
    
    $events = $contactApi->getEvents($id, $search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page);
    

    Warining: Deprecated. Use getActivityForContact instead.

    ** Query Parameters **

    Name Description
    id Contact ID
    filters[search] String or search command to filter events by.
    filters[includeEvents][] Array of event types to include.
    filters[excludeEvents][] Array of event types to exclude.
    order Array of Column and Direction [COLUMN, DIRECTION].
    page What page number to load
    {
      "events":[
        {
          "event":"lead.identified",
          "icon":"fa-user",
          "eventType":"Contact identified",
          "eventPriority":-4,
          "timestamp":"2016-06-09T21:39:08+00:00",
          "featured":true
        }
      ],
      "filters":{
        "search":"",
        "includeEvents":[
          "lead.identified"
        ],
        "excludeEvents":[]
      },
      "order":[
        "",
        "ASC"
      ],
      "types":{
        "lead.ipadded":"Accessed from IP",
        "asset.download":"Asset downloaded",
        "campaign.event":"Campaign action triggered",
        "lead.create":"Contact created",
        "lead.identified":"Contact identified",
        "lead.donotcontact":"Do not contact",
        "email.read":"Email read",
        "email.sent":"Email sent",
        "email.failed":"Failed",
        "form.submitted":"Form submitted",
        "page.hit":"Page hit",
        "point.gained":"Point gained",
        "stage.changed":"Stage changed",
        "lead.utmtagsadded":"UTM tags recorded",
        "page.videohit":"Video View Event"
      },
      "total":1,
      "page":1,
      "limit":25,
      "maxPages":1
    }
    

    Get a list of contact events the contact created.

    HTTP Request

    GET /contacts/ID/events

    Warining: Deprecated. Use GET /contacts/ID/activity instead.

    Response

    Expected response code: 200

    ** List Properties **

    Name Type Description
    events array List of events
    event string ID of the event type
    icon string Icon class from FontAwesome
    eventType string Human name of the event
    eventPriority string Priority of the event
    timestamp timestamp Date and time when the event was created
    featured bool Flag whether the event is featured
    filters array Filters used in the query
    order array Ordering used in the query
    types array Array of available event types
    total int Total number of events in the request
    page int Current page number
    limit int Limit of events per page
    maxPages int How many pages of events are there

    Get activity events for specific contact

    <?php
    
    $events = $contactApi->getActivityForContact($id, $search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page, $dateFrom, $dateTo);
    

    ** Query Parameters **

    Name Description
    id Contact ID
    filters[search] String or search command to filter events by.
    filters[includeEvents][] Array of event types to include.
    filters[excludeEvents][] Array of event types to exclude.
    filters[dateFrom] Date from filter. Must be type of \DateTime for the PHP API libary and in format Y-m-d H:i:s for HTTP param
    filters[dateTo] Date to filter. Must be type of \DateTime for the PHP API libary and in format Y-m-d H:i:s for HTTP param
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    page What page number to load
    {
      "events":[
        {
          "event":"lead.identified",
          "icon":"fa-user",
          "eventType":"Contact identified",
          "eventPriority":-4,
          "timestamp":"2016-06-09T21:39:08+00:00",
          "featured":true
        }
      ],
      "filters":{
        "search":"",
        "includeEvents":[
          "lead.identified"
        ],
        "excludeEvents":[]
      },
      "order":[
        "",
        "ASC"
      ],
      "types":{
        "asset.download": "Asset downloaded",
        "campaign.event": "Campaign action triggered",
        "campaign.event.scheduled": "Campaign event scheduled",
        "lead.donotcontact": "Do not contact",
        "email.failed": "Email failed",
        "email.read": "Email read",
        "email.sent": "Email sent",
        "form.submitted": "Form submitted",
        "lead.imported": "Imported",
        "page.hit": "Page hit",
        "point.gained": "Point gained",
        "stage.changed": "Stage changed",
        "lead.utmtagsadded": "UTM tags recorded",
        "page.videohit": "Video view event"
      },
      "total":1,
      "page":1,
      "limit":25,
      "maxPages":1
    }
    

    Get a list of contact events the contact had created.

    HTTP Request

    GET /contacts/ID/activity

    Response

    Expected response code: 200

    ** List Properties **

    Name Type Description
    events array List of events
    event string ID of the event type
    icon string Icon class from FontAwesome
    eventType string Human name of the event
    eventPriority string Priority of the event
    timestamp timestamp Date and time when the event was created
    featured bool Flag whether the event is featured
    filters array Filters used in the query
    order array Ordering used in the query
    types array Array of available event types
    total int Total number of events in the request
    page int Current page number
    limit int Limit of events per page
    maxPages int How many pages of events are there

    Get Activity events for all contacts

    <?php
    
    $events = $contactApi->getActivity($search, $includeEvents, $excludeEvents, $orderBy, $orderByDir, $page, $dateFrom, $dateTo);
    

    ** Query Parameters **

    Name Description
    filters[search] String or search command to filter events by.
    filters[includeEvents][] Array of event types to include.
    filters[excludeEvents][] Array of event types to exclude.
    filters[dateFrom] Date from filter. Must be type of \DateTime for the PHP API libary and in format Y-m-d H:i:s for HTTP param
    filters[dateTo] Date to filter. Must be type of \DateTime for the PHP API libary and in format Y-m-d H:i:s for HTTP param
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    page What page number to load
     {
      "events": [
        {
          "event": "meeting.attended",
          "eventId": "meeting.attended65",
          "eventLabel": "Attended meeting - Mautic instance",
          "eventType": "Meeting attendance",
          "timestamp": "2017-08-03T21:03:04+00:00",
          "contactId": "12180",
          "details": {
            "eventName": "mautic-instance",
            "eventId": "371343405",
            "eventDesc": "Mautic instance",
            "joinUrl": ""
          }
        },
        {
          "event": "webinar.attended",
          "eventId": "webinar.attended67",
          "eventLabel": "Attended webinar - Mautic",
          "eventType": "Webinar attendance",
          "timestamp": "2017-08-03T21:03:04+00:00",
          "contactId": "12180",
          "details": {
            "eventName": "mautic",
            "eventId": "530287395",
            "eventDesc": "Mautic",
            "joinUrl": ""
          }
        },
        {
          "event": "webinar.registered",
          "eventId": "webinar.registered66",
          "eventLabel": "Registered for webinar - Mautic",
          "eventType": "Webinar registered for",
          "timestamp": "2017-08-03T21:03:04+00:00",
          "contactId": "12180",
          "details": {
            "eventName": "mautic",
            "eventId": "530287395",
            "eventDesc": "Mautic",
            "joinUrl": "https://global.gotowebinar.com/join/xxx/xxx"
          }
        },
        {
          "event": "campaign.event",
          "eventId": "campaign.event892",
          "eventLabel": {
            "label": "Contact field value \/ Campaign Date",
            "href": "\/s\/campaigns\/view\/498"
          },
          "eventType": "Campaign action triggered",
          "timestamp": "2017-08-03T00:58:25+00:00",
          "contactId": "12281",
          "details": {
            "log": {
              "dateTriggered": "2017-08-03T00:58:25+00:00",
              "metadata": [],
              "type": "lead.field_value",
              "isScheduled": "0",
              "logId": "892",
              "eventId": "1457",
              "campaignId": "498",
              "eventName": "Contact field value",
              "campaignName": "Campaign Date"
            }
          }
        },
        {
          "event": "email.sent",
          "eventId": "email.sent796",
          "eventLabel": {
            "label": "2017-05-23 - Email - Leads - Nurture Flow (Monica) 1",
            "href": "http:\/\/mautic.dev\/email\/view\/597a116ae69ca",
            "isExternal": true
          },
          "eventType": "Email sent",
          "timestamp": "2017-07-27T16:14:34+00:00",
          "contactId": "16419",
          "details": {
            "stat": {
              "id": "796",
              "dateSent": "2017-07-27T16:14:34+00:00",
              "subject": "How to make the case for digital",
              "isRead": "0",
              "isFailed": "0",
              "viewedInBrowser": "0",
              "retryCount": "0",
              "idHash": "597a116ae69ca",
              "openDetails": [],
              "storedSubject": "How to make the case for digital",
              "timeToRead": false,
              "emailId": "78",
              "emailName": "2017-05-23 - Email - Leads - Nurture Flow (Monica) 1"
            },
            "type": "sent"
          }
        },
        {
          "event": "email.read",
          "eventId": "email.read769",
          "eventLabel": {
            "label": "Custom Email: device test",
            "href": "http:\/\/mautic.dev\/email\/view\/5966b0cd571f4",
            "isExternal": true
          },
          "eventType": "Email read",
          "timestamp": "2017-07-12T23:30:56+00:00",
          "contactId": "13930",
          "details": {
            "stat": {
              "id": "769",
              "dateRead": "2017-07-12T23:30:56+00:00",
              "dateSent": "2017-07-12T23:29:17+00:00",
              "isRead": "1",
              "isFailed": "0",
              "viewedInBrowser": "0",
              "retryCount": "0",
              "idHash": "5966b0cd571f4",
              "openDetails": [
                {
                  "datetime": "2017-07-12 23:30:56",
                  "useragent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/59.0.3071.115 Safari\/537.36",
                  "inBrowser": false
                },
                {
                  "datetime": "2017-07-13 02:18:51",
                  "useragent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/59.0.3071.115 Safari\/537.36",
                  "inBrowser": false
                }
              ],
              "storedSubject": "device test",
              "timeToRead": "PT1M39S"
            },
            "type": "read"
          }
        },
        {
          "event": "lead.ipadded",
          "eventId": "lead.ipadded3263",
          "eventLabel": "127.0.0.1",
          "eventType": "Accessed from IP",
          "timestamp": "2017-07-27T03:09:09+00:00",
          "contactId": "3263",
          "details": []
        },
        {
          "event": "form.submitted",
          "eventId": "form.submitted503",
          "eventLabel": {
            "label": "3586 Test",
            "href": "\/s\/forms\/view\/143"
          },
          "eventType": "Form submitted",
          "timestamp": "2017-07-27T03:09:07+00:00",
          "contactId": "16417",
          "details": {
            "submission": {
              "id": 503,
              "ipAddress": {
                "ip": "127.0.0.1"
              },
              "form": {
                "id": 143,
                "name": "3586 Test",
                "alias": "3586_test"
              },
              "dateSubmitted": "2017-07-27T03:09:07+00:00",
              "referer": "http:\/\/mautic.dev\/form\/143",
              "results": {
                "form_id": "143",
                "email": "formtest7@test.com",
                "f_name": ""
              }
            },
            "form": {
              "id": 143,
              "name": "3586 Test",
              "alias": "3586_test"
            },
            "page": {}
          }
        },
        {
          "event": "page.hit",
          "eventLabel": {
            "label": "Test",
            "href": "\/s\/pages\/view\/8"
          },
          "eventType": "Page hit",
          "timestamp": "2017-07-21T20:36:49+00:00",
          "contactId": "16380",
          "details": {
            "hit": {
              "userAgent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/59.0.3071.115 Safari\/537.36",
              "dateHit": "2017-07-21T20:36:49+00:00",
              "url": "http:\/\/mautic.dev\/uncategorized\/translation-test1",
              "query": {
                "pageUrl": "http:\/\/mautic.dev\/uncategorized\/translation-test1"
              },
              "clientInfo": "a:6:{s:4:\"type\";s:7:\"browser\";s:4:\"name\";s:6:\"Chrome\";s:10:\"short_name\";s:2:\"CH\";s:7:\"version\";s:4:\"59.0\";s:6:\"engine\";s:5:\"Blink\";s:14:\"engine_version\";s:0:\"\";}",
              "device": "desktop",
              "deviceOsName": "Mac",
              "deviceBrand": "",
              "deviceModel": "",
              "pageId": "8"
            }
          }
        },
        {
          "event": "point.gained",
          "eventLabel": "2: Page Hit Test \/ 20",
          "eventType": "Point gained",
          "timestamp": "2017-07-20T22:38:28+00:00",
          "contactId": "16379",
          "details": {
            "log": {
              "eventName": "2: Page Hit Test",
              "actionName": "hit",
              "dateAdded": "2017-07-20T22:38:28+00:00",
              "type": "url",
              "delta": "20",
              "id": "2"
            }
          }
        },
        {
          "event": "lead.imported",
          "eventId": "lead.imported6324",
          "eventType": "Imported",
          "eventLabel": {
            "label": "Contact import failed from FakeNameGenerator.com_20d05d9c.csv",
            "href": "\/s\/contacts\/import\/view\/4"
          },
          "timestamp": "2017-07-17T21:42:35+00:00",
          "details": {
            "id": "6324",
            "bundle": "lead",
            "object": "import",
            "action": "failed",
            "properties": {
              "line": 2001,
              "file": "FakeNameGenerator.com_20d05d9c.csv",
              "error": "No data found"
            },
            "userId": "2",
            "userName": "Bob Smith",
            "objectId": "4",
            "dateAdded": "2017-07-17T21:42:35+00:00"
          }
        },
        {
          "event": "asset.download",
          "eventId": "asset.download11",
          "eventLabel": {
            "label": "Download Mautic",
            "href": "\/s\/assets\/view\/1"
          },
          "eventType": "Asset downloaded",
          "timestamp": "2017-04-04T01:49:13+00:00",
          "details": {
            "asset": {
              "id": 1,
              "title": "Download Mautic",
              "alias": "download-mautic",
              "description": "test"
            },
            "assetDownloadUrl": "http:\/\/mautic.dev\/asset\/1:download-mautic"
          }
        },
      ],
      "filters": {
        "search": "",
        "includeEvents": [],
        "excludeEvents": []
      },
      "order": [
        "timestamp",
        "DESC"
      ],
      "types": {
        "lead.ipadded": "Accessed from IP",
        "asset.download": "Asset downloaded",
        "meeting.attended": "Attended meeting",
        "webinar.attended": "Attended webinar",
        "campaign.event": "Campaign action triggered",
        "campaign.event.scheduled": "Campaign event scheduled",
        "lead.donotcontact": "Do not contact",
        "email.failed": "Email failed",
        "email.read": "Email read",
        "email.sent": "Email sent",
        "form.submitted": "Form submitted",
        "lead.imported": "Imported",
        "page.hit": "Page hit",
        "point.gained": "Point gained",
        "meeting.registered": "Registered for meeting",
        "webinar.registered": "Registration to Webinar",
        "stage.changed": "Stage changed",
        "lead.utmtagsadded": "UTM tags recorded",
        "page.videohit": "Video view event"
      },
      "total": 12,
      "page": 1,
      "limit": 25,
      "maxPages": 1
    }
    

    HTTP Request

    GET /contacts/activity

    Response

    Expected response code: 200

    ** List Properties **

    Name Type Description
    events array List of events
    event string ID of the event type
    icon string Icon class from FontAwesome
    eventType string Human name of the event
    eventPriority string Priority of the event
    contactId ID of the contact who created the event
    timestamp timestamp Date and time when the event was created
    featured bool Flag whether the event is featured
    filters array Filters used in the query
    order array Ordering used in the query
    types array Array of available event types
    total int Total number of events in the request
    page int Current page number
    limit int Limit of events per page
    maxPages int How many pages of events are there

    Get Contact's Companies

    <?php
    
    $companies = $contactApi->getContactCompanies($contactId);
    
    ```json
    {
      "total":1,
      "companies":[
        {
          "company_id":"420",
          "date_associated":"2016-12-27 15:03:43",
          "is_primary":"0",
          "companyname":"test",
          "companyemail":"test@company.com",
          "companycity":"Raleigh",
          "score":"0",
          "date_added":"2016-12-27 15:03:42"
        }
      ]
    }
    

    Get a list of contact's companies the contact belongs to.

    HTTP Request

    GET /contacts/ID/companies

    Response

    Expected response code: 200

    List Properties

    Name Type Description
    company_id int Company ID
    date_associated datetime Date and time when the contact was associated to the company
    date_added datetime Date and time when the company was created
    is_primary bool Flag whether the company association is primary (current)
    companyname string Name of the company
    companyemail string Email of the company
    companycity string City of the company
    score int Score of the company

    Get Contact's Devices

    <?php
    
    $devices = $contactApi->getContactDevices($contactId);
    
    ```json
    {
      "total":1,
      "devices":[
        {
          "id":60,
          "lead":[],
          "clientInfo":[],
          "device":"desktop",
          "deviceOsName":"Ubuntu",
          "deviceOsShortName":"UBT",
          "deviceOsPlatform":"x64"
        }
      ]
    }
    

    Get a list of contact's devices the contact has used.

    HTTP Request

    GET /contacts/ID/devices

    Response

    Expected response code: 200

    List Properties

    Name Type Description
    id int Device ID
    clientInfo array Array with various information about the client (browser)
    device string Device type; desktop, mobile..
    deviceOsName string Full device OS name
    deviceOsShortName string Short device OS name
    deviceOsPlatform string OS platform

    Data - Dashboard widget data

    Use this endpoint to obtain details on Mautic's dashboard statistical data.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth   = new ApiAuth();
    $auth       = $initAuth->newAuth($settings);
    $apiUrl     = "https://your-mautic.com";
    $api        = new MauticApi();
    $contactApi = $api->newApi("data", $auth, $apiUrl);
    

    Get list of available widget types

    <?php
    $data = $dataApi->getList();
    

    HTTP Request

    GET /data

    Expected Response Code: 200

    {
        "success":1,
        "types":{
            "Core Widgets":{
                "recent.activity":"Recent Activity"
            },
            "Contact Widgets":{
                "created.leads.in.time":"Created contacts in time",
                "anonymous.vs.identified.leads":"Anonymous vs identified contacts",
                "map.of.leads":"Map",
                "top.lists":"Top segments",
                "top.creators":"Top contact creators",
                "top.owners":"Top contact owners",
                "created.leads":"Created contacts"
            },
            "Page Widgets":{
                "page.hits.in.time":"Page visits in time",
                "unique.vs.returning.leads":"Unique vs returning visitors",
                "dwell.times":"Dwell times",
                "popular.pages":"Popular landing pages",
                "created.pages":"Created Landing pages"
            },
            "Point Widgets":{
                "points.in.time":"Points in time"
            },
            "Form Widgets":{
                "submissions.in.time":"Submissions in time",
                "top.submission.referrers":"Top submission referrers",
                "top.submitters":"Top submitters",
                "created.forms":"Created forms"
            },
            "Email Widgets":{
                "emails.in.time":"Emails in time",
                "sent.email.to.contacts":"Sent email to contacts",
                "most.hit.email.redirects":"Most hit email redirects",
                "ignored.vs.read.emails":"Ignored vs read",
                "upcoming.emails":"Upcoming emails",
                "most.sent.emails":"Most sent emails",
                "most.read.emails":"Most read emails",
                "created.emails":"Created emails"
            },
            "Asset Widgets":{
                "asset.downloads.in.time":"Downloads in time",
                "unique.vs.repetitive.downloads":"Unique vs repetitive downloads",
                "popular.assets":"Popular assets",
                "created.assets":"Created assets"
            },
            "Campaign Widgets":{
                "events.in.time":"Events triggered in time",
                "leads.added.in.time":"Leads added in time"
            }
        }
    }
    

    Get an individual widget data by type.

    <?php
    $data = $dataApi->get($type, $options);
    

    HTTP Request

    GET /data/{type}?dateFrom={YYYY-mm-dd}&dateTo={YYYY-mm-dd}&timeUnit={m}

    Returns response which can be directly visualized byt the chartJS library.

    Response

    Expected Response Code: 200

    {
        "success":1,
        "cached":false,
        "execution_time":0.043900966644287,
        "data":{
            "chartType":"line",
            "chartHeight":220,
            "chartData":{
                "labels":[
                    "Jan 2016",
                    "Feb 2016",
                    "Mar 2016",
                    "Apr 2016",
                    "May 2016"
                ],
                "datasets":[{
                    "label":"Submission Count",
                    "data":[
                        12,
                        6,
                        0,
                        0,
                        0
                    ],
                    "fillColor":"rgba(78,93,157,0.1)",
                    "strokeColor":"rgba(78,93,157,0.8)",
                    "pointColor":"rgba(78,93,157,0.75)",
                    "pointHighlightStroke":"rgba(78,93,157,1)"
                }]
            }
        }
    }
    

    HTTP Request

    GET /data/{type}?dateFrom={YYYY-mm-dd}&dateTo={YYYY-mm-dd}&timeUnit={m}&dataFormat={raw}

    Returns raw format which can be more easily processed.

    Response

    Expected Response Code: 200

    {
        "success":1,
        "cached":false,
        "execution_time":0.039958000183105,
        "data":{
            "Submission Count":{
                "Jan 2016":12,
                "Feb 2016":6,
                "Mar 2016":0,
                "Apr 2016":0,
                "May 2016":0
            }
        }
    }
    

    "Emails in time" widget

    Filter parameters

    filtercompanyId Filter only emails from contacts assigned to provided company.

    filter[campaignId (int) Filter only emails from contacts that were sent as part of provided campaign.

    filtersegmentId Filter only emails from contacts assigned to provided segment.

    Dataset parameter

    dataset (array) - sent - opened - unsubscribed - clicked - bounced - failed Provide more datasets in response based on request.

    HTTP Request:

    GET /api/data/emails.in.time?dateFrom={YYYY-mm-dd}&dateTo={YYYY-mm-dd}&timeUnit={m}&filter[campaignId]={int}&filter[companyId]={int}&filter[segmentId]={int}&withCounts&dataset[]=sent&dataset[]=opened&dataset[]=unsubscribed&dataset[]=clicked

    "Sent email to contacts" widget

    Filter parameters

    filtercompanyId Filter only emails from contacts assigned to provided company.

    filter[campaignId (int) Filter only emails from contacts that were sent as part of provided campaign.

    filtersegmentId Filter only emails from contacts assigned to provided segment.

    HTTP Request:

    GET /api/data/sent.email.to.contacts?dateFrom={YYYY-mm-dd}&dateTo={YYYY-mm-dd}&timeUnit={m}&filter[campaignId]={int}&filter[companyId]={int}&filter[segmentId]={int}&limit=10&offset=0

    "Most hit email redirects" widgets

    Filter parameters

    filtercompanyId Filter only emails from contacts assigned to provided company.

    filter[campaignId (int) Filter only emails from contacts that were sent as part of provided campaign.

    filtersegmentId Filter only emails from contacts assigned to provided segment.

    HTTP Request:

    GET /api/data/most.hit.email.redirects?dateFrom={YYYY-mm-dd}&dateTo={YYYY-mm-dd}&timeUnit={m}&filter[campaignId]={int}&filter[companyId]={int}&filter[segmentId]={int}&limit=10&offset=0

    Available data URL query params

    Name|Type|Example|Description ----|----|----------- timezone|string|America/New_York|PHP timezone dateFrom|string|2016-28-03|Date from in the YYYY-mm-dd HH:ii:ss format dateTo|string|2016-28-04|Date to in the YYYY-mm-dd HH:ii:ss format timeUnit|string|m|Date/Time unit. Available options: Y, m, W, d, H limit|int|10|Limit of the table widget items filter|array|[lead_id => 23]|filters which should be applied to the SQL query

    Dynamic Content

    Use this endpoint to obtain details on Mautic's web dynamic content.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth         = new ApiAuth();
    $auth             = $initAuth->newAuth($settings);
    $apiUrl           = "https://your-mautic.com";
    $api              = new MauticApi();
    $dynamicContentApi = $api->newApi("dynamicContents", $auth, $apiUrl);
    

    Get Dynamic Content

    <?php
    
    //...
    $dynamicContent = $dynamicContentApi->get($id);
    
    {
        "dynamicContent":{
            "isPublished":true,
            "dateAdded":"2016-06-20T11:26:51+00:00",
            "createdBy":1,
            "createdByUser":"John Doe",
            "dateModified":"2016-08-08T16:36:27+00:00",
            "modifiedBy":1,
            "modifiedByUser":"John Doe",
            "id":1,
            "name":"DC13",
            "category":null,
            "publishUp":null,
            "publishDown":null,
            "sentCount":0,
            "variantParent":null,
            "variantChildren":[]
        }
    }
    

    Get an individual dynamicContent by ID.

    HTTP Request

    GET /dynamiccontents/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Dynamic Content Properties

    Name Type Description
    id int ID of the dynamic content
    name string Name of the dynamic content
    description string/null Description of the dynamic content
    isPublished bool Published state
    publishUp datetime/null Date/time when the dynamic content should be published
    publishDown datetime/null Date/time the dynamic content should be un published
    dateAdded datetime Date/time dynamic content was created
    createdBy int ID of the user that created the dynamic content
    createdByUser string Name of the user that created the dynamic content
    dateModified datetime/null Date/time dynamic content was last modified
    modifiedBy int ID of the user that last modified the dynamic content
    modifiedByUser string Name of the user that last modified the dynamic content
    variantChildren array Array of Dynamic Content entities for variants of this landing dynamic content
    variantParent object The parent/main dynamic content if this is a variant (A/B test)
    sentCount int Count of how many times the dynamic content was sent

    List Dynamic Contents

    <?php
    // ...
    
    $dynamicContents = $dynamicContentApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total":30,
        "dynamicContents":[
            {
                "isPublished":true,
                "dateAdded":"2016-06-20T11:27:09+00:00",
                "createdBy":1,
                "createdByUser":"John Doe",
                "dateModified":"2016-08-22T17:14:01+00:00",
                "modifiedBy":1,
                "modifiedByUser":"John Doe",
                "id":2,
                "name":"CD2",
                "category":null,
                "publishUp":null,
                "publishDown":null,
                "sentCount":0,
                "variantParent":null,
                "variantChildren":[]
            }
        ]
    }
    

    HTTP Request

    GET /dynamiccontents

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Dynamic Content.

    Create Dynamic Content

    <?php
    
    $data = array(
        'name'        => 'Dynamic Content A',
        'isPublished' => 1
    );
    
    $dynamicContent = $dynamicContentApi->create($data);
    

    Create a new dynamicContent.

    HTTP Request

    POST /dynamiccontents/new

    Post Parameters

    Name Type Description
    id int ID of the dynamic content
    name string Name of the dynamic content
    description string/null Description of the dynamic content
    isPublished bool Published state
    publishUp datetime/null Date/time when the dynamic content should be published
    publishDown datetime/null Date/time the dynamic content should be un published
    dateAdded datetime Date/time dynamic content was created
    createdBy int ID of the user that created the dynamic content
    createdByUser string Name of the user that created the dynamic content
    dateModified datetime/null Date/time dynamic content was last modified
    modifiedBy int ID of the user that last modified the dynamic content
    modifiedByUser string Name of the user that last modified the dynamic content
    variantChildren array Array of Dynamic Content entities for variants of this landing dynamic content
    variantParent object The parent/main dynamic content if this is a variant (A/B test)
    sentCount int Count of how many times the dynamic content was sent

    Response

    Expected Response Code: 201

    Properties

    Same as Get Dynamic Content.

    Edit Dynamic Content

    <?php
    
    $id   = 1;
    $data = array(
        'name'        => 'New dynamicContent name',
        'isPublished' => 0
    );
    
    // Create new a dynamicContent of ID 1 is not found?
    $createIfNotFound = true;
    
    $dynamicContent = $dynamicContentApi->edit($id, $data, $createIfNotFound);
    

    Edit a new dynamicContent. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a dynamicContent if the given ID does not exist and clears all the dynamic content information, adds the information from the request. PATCH fails if the dynamic content with the given ID does not exist and updates the dynamic content field values with the values form the request.

    HTTP Request

    To edit a dynamicContent and return a 404 if the dynamic content is not found:

    PATCH /dynamiccontents/ID/edit

    To edit a dynamicContent and create a new one if the dynamic content is not found:

    PUT /dynamiccontents/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the dynamic content
    name string Name of the dynamic content
    description string/null Description of the dynamic content
    isPublished bool Published state
    publishUp datetime/null Date/time when the dynamic content should be published
    publishDown datetime/null Date/time the dynamic content should be un published
    dateAdded datetime Date/time dynamic content was created
    createdBy int ID of the user that created the dynamic content
    createdByUser string Name of the user that created the dynamic content
    dateModified datetime/null Date/time dynamic content was last modified
    modifiedBy int ID of the user that last modified the dynamic content
    modifiedByUser string Name of the user that last modified the dynamic content
    variantChildren array Array of Dynamic Content entities for variants of this landing dynamic content
    variantParent object The parent/main dynamic content if this is a variant (A/B test)
    sentCount int Count of how many times the dynamic content was sent

    Response

    If PUT, the expected response code is 200 if the dynamic content was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Dynamic Content.

    Delete Dynamic Content

    <?php
    
    $dynamicContent = $dynamicContentApi->delete($id);
    

    Delete a dynamicContent.

    HTTP Request

    DELETE /dynamiccontents/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Dynamic Content.

    Emails

    Use this endpoint to obtain details, create, update or delete Mautic's emails.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $emailApi = $api->newApi("emails", $auth, $apiUrl);
    

    Get Email

    <?php
    
    //...
    $email = $emailApi->get($id);
    
    {  
      "email":{  
        "isPublished":true,
        "dateAdded":"2016-10-25T18:51:17+00:00",
        "createdBy":1,
        "createdByUser":"John Doe",
        "dateModified":null,
        "modifiedBy":null,
        "modifiedByUser":null,
        "id":560,
        "name":"test",
        "subject":"API test email",
        "language":"en",
        "category":null,
        "fromAddress":null,
        "fromName":null,
        "replyToAddress":null,
        "bccAddress":null,
        "customHtml":"<h1>Hi there!<\/h1>",
        "plainText":null,
        "template":null,
        "emailType":"list",
        "publishUp":null,
        "publishDown":null,
        "readCount":0,
        "sentCount":0,
        "revision":1,
        "assetAttachments":[],
        "variantStartDate":null,
        "variantSentCount":0,
        "variantReadCount":0,
        "variantParent":null,
        "variantChildren":[],
        "translationParent":null,
        "translationChildren":[],
        "unsubscribeForm":null,
        "dynamicContent":[  
          {  
            "tokenName":null,
            "content":null,
            "filters":[  
              {  
                "content":null,
                "filters":[  
                  {  
                    "glue":null,
                    "field":null,
                    "object":null,
                    "type":null,
                    "operator":null,
                    "display":null,
                    "filter":null
                  }
                ]
              }
            ]
          }
        ],
        "lists":[  
          {  
            "createdByUser":"John Doe",
            "modifiedByUser":null,
            "id":256,
            "name":"test",
            "alias":"test29",
            "description":null
          }
        ]
      }
    }
    

    Get an individual email by ID.

    HTTP Request

    GET /emails/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Email Properties

    Name Type Description
    id int ID of the email
    name string Internal name of the email
    subject stringl Subject of the email
    fromAddress string The from email address if it's different than the one in the Mautic configuration
    fromName string The from name if it's different than the one in the Mautic configuration
    replyToAddress string The reply to email address if it's different than the one in the Mautic configuration
    bccAddress string The BCC email address if it's different than the one in the Mautic configuration
    isPublished bool Published state
    publishUp datetime/null Date/time when the email should be published
    publishDown datetime/null Date/time the email should be un published
    dateAdded datetime Date/time email was created
    createdBy int ID of the user that created the email
    createdByUser string Name of the user that created the email
    dateModified datetime/null Date/time email was last modified
    modifiedBy int ID of the user that last modified the email
    modifiedByUser string Name of the user that last modified the email
    language string Language locale of the email
    readCount int Total email read count
    sentCount int Total email sent count
    revision int Email revision
    customHtml string The HTML content of the email
    plainText string The plain text content of the email
    template string The name of the template used as the base for the email
    emailType string If it is a segment (former list) email or template email. Possible values are 'list' and 'template'
    translationChildren array Array of Page entities for translations of this landing page
    translationParent object The parent/main page if this is a translation
    variantSentCount int Sent count since variantStartDate
    variantReadCount int Read count since variantStartDate
    variantChildren array Array of Email entities for variants of this landing email
    variantParent object The parent/main email if this is a variant (A/B test)
    variantSettings array The properties of the A/B test
    variantStartDate datetime/null The date/time the A/B test began
    category object/null Category information
    unsubscribeForm int Id of the form displayed in the unsubscribe page
    dynamicContent object Dynamic content configuration
    lists array Array of segment IDs which should be added to the segment email
    assetAttachments array asset IDs Array for email attachment

    List Emails

    <?php
    // ...
    
    $emails = $emailApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "emails": [
            {  
                "isPublished":true,
                "dateAdded":"2016-10-25T18:51:17+00:00",
                "createdBy":1,
                "createdByUser":"John Doe",
                "dateModified":null,
                "modifiedBy":null,
                "modifiedByUser":null,
                "id":560,
                "name":"test",
                "subject":"API test email",
                "language":"en",
                "category":null,
                "fromAddress":null,
                "fromName":null,
                "replyToAddress":null,
                "bccAddress":null,
                "customHtml":"<h1>Hi there!<\/h1>",
                "plainText":null,
                "template":null,
                "emailType":"list",
                "publishUp":null,
                "publishDown":null,
                "readCount":0,
                "sentCount":0,
                "revision":1,
                "assetAttachments":[],
                "variantStartDate":null,
                "variantSentCount":0,
                "variantReadCount":0,
                "variantParent":null,
                "variantChildren":[],
                "translationParent":null,
                "translationChildren":[],
                "unsubscribeForm":null,
                "dynamicContent":[  
                  {  
                    "tokenName":null,
                    "content":null,
                    "filters":[  
                      {  
                        "content":null,
                        "filters":[  
                          {  
                            "glue":null,
                            "field":null,
                            "object":null,
                            "type":null,
                            "operator":null,
                            "display":null,
                            "filter":null
                          }
                        ]
                      }
                    ]
                  }
                ],
                "lists":[  
                  {  
                    "createdByUser":"John Doe",
                    "modifiedByUser":null,
                    "id":256,
                    "name":"test",
                    "alias":"test29",
                    "description":null
                  }
                ]
              }
        ]
    }
    

    HTTP Request

    GET /emails

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Email.

    Create Email

    <?php 
    
    $data = array(
        'title'        => 'Email A',
        'description' => 'This is my first email created via API.',
        'isPublished' => 1
    );
    
    $email = $emailApi->create($data);
    

    Create a new email.

    HTTP Request

    POST /emails/new

    Post Parameters

    Name Type Description
    id int ID of the email
    name string Internal name of the email
    subject stringl Subject of the email
    fromAddress string The from email address if it's different than the one in the Mautic configuration
    fromName string The from name if it's different than the one in the Mautic configuration
    replyToAddress string The reply to email address if it's different than the one in the Mautic configuration
    bccAddress string The BCC email address if it's different than the one in the Mautic configuration
    isPublished bool Published state
    publishUp datetime/null Date/time when the email should be published
    publishDown datetime/null Date/time the email should be un published
    language string Language locale of the email
    readCount int Total email read count
    sentCount int Total email sent count
    revision int Email revision
    customHtml string The HTML content of the email
    plainText string The plain text content of the email
    template string The name of the template used as the base for the email
    emailType string If it is a segment (former list) email or template email. Possible values are 'list' and 'template'
    translationChildren array Array of Page entities for translations of this landing page
    translationParent object The parent/main page if this is a translation
    variantSentCount int Sent count since variantStartDate
    variantReadCount int Read count since variantStartDate
    variantChildren array Array of Email entities for variants of this landing email
    variantParent object The parent/main email if this is a variant (A/B test)
    variantSettings array The properties of the A/B test
    variantStartDate datetime/null The date/time the A/B test began
    category object/null Category information
    unsubscribeForm int Id of the form displayed in the unsubscribe page
    dynamicContent object Dynamic content configuration
    lists array Array of segment IDs which should be added to the segment email

    Response

    Expected Response Code: 201

    Properties

    Same as Get Email.

    Edit Email

    <?php
    
    $id   = 1;
    $data = array(
        'title'        => 'New email title',
        'isPublished' => 0
    );
    
    // Create new a email of ID 1 is not found?
    $createIfNotFound = true;
    
    $email = $emailApi->edit($id, $data, $createIfNotFound);
    

    Edit a new email. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a email if the given ID does not exist and clears all the email information, adds the information from the request. PATCH fails if the email with the given ID does not exist and updates the email field values with the values form the request.

    HTTP Request

    To edit a email and return a 404 if the email is not found:

    PATCH /emails/ID/edit

    To edit a email and create a new one if the email is not found:

    PUT /emails/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the email
    name string Internal name of the email
    subject stringl Subject of the email
    fromAddress string The from email address if it's different than the one in the Mautic configuration
    fromName string The from name if it's different than the one in the Mautic configuration
    replyToAddress string The reply to email address if it's different than the one in the Mautic configuration
    bccAddress string The BCC email address if it's different than the one in the Mautic configuration
    isPublished bool Published state
    publishUp datetime/null Date/time when the email should be published
    publishDown datetime/null Date/time the email should be un published
    language string Language locale of the email
    readCount int Total email read count
    sentCount int Total email sent count
    revision int Email revision
    customHtml string The HTML content of the email
    plainText string The plain text content of the email
    template string The name of the template used as the base for the email
    emailType string If it is a segment (former list) email or template email. Possible values are 'list' and 'template'
    translationChildren array Array of Page entities for translations of this landing page
    translationParent object The parent/main page if this is a translation
    variantSentCount int Sent count since variantStartDate
    variantReadCount int Read count since variantStartDate
    variantChildren array Array of Email entities for variants of this landing email
    variantParent object The parent/main email if this is a variant (A/B test)
    variantSettings array The properties of the A/B test
    variantStartDate datetime/null The date/time the A/B test began
    category object/null Category information
    unsubscribeForm int Id of the form displayed in the unsubscribe page
    dynamicContent object Dynamic content configuration
    lists array Array of segment IDs which should be added to the segment email

    Response

    If PUT, the expected response code is 200 if the email was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Email.

    Delete Email

    <?php
    
    $email = $emailApi->delete($id);
    

    Delete a email.

    HTTP Request

    DELETE /emails/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Email.

    Send Email to Contact

    <?php
    
    $email = $emailApi->sendToContact($emailId, $contactId);
    

    Send a predefined email to existing contact.

    Assets can be referenced for attaching documents (either ids of existing assets or ids returned by the Create Asset).

    HTTP Request

    POST /emails/ID/contact/CONTACT_ID/send

    Post Parameters

    Name Type Description
    tokens array Array of tokens in email
    assetAttachments array Array of asset ids

    Response

    Expected Response Code: 200

    Properties json { "success": 1 }

    Send Email to Segment

    <?php
    
    $email = $emailApi->send($id);
    

    Send a segment email to linked segment(s).

    HTTP Request

    POST /emails/ID/send

    Response

    Expected Response Code: 200

    Properties json { "success": 1, "sentCount": 1, "failedCount": 0 }

    Create a reply to a send email send row

    This endpoint can create a record that a specific email stat row received a reply. It will also mark an email send stat as read.

    HTTP Request

    POST /emails/reply/TRACKING_HASH

    Tracking hash is created as unique hash for each email send stat record.

    Response

    Expected Response Code: 200

    Properties json { "success": 1, }

    Fields

    Use this endpoint to work with Mautic's contact/company fields.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $assetApi = $api->newApi("assets", $auth, $apiUrl);
    
    // Get contact field context:
    $fieldApi = $api->newApi("contactFields", $auth, $apiUrl);
    
    // Or use 'companyFields' for company fields:
    $fieldApi = $api->newApi("companyFields", $auth, $apiUrl);
    

    Get Field

    <?php
    
    //...
    $field = $fieldApi->get($id);
    
    {  
      "field":{  
        "isPublished":true,
        "dateAdded":"2016-11-10T13:02:52+00:00",
        "createdBy":1,
        "createdByUser":"John Doe",
        "dateModified":null,
        "modifiedBy":null,
        "modifiedByUser":null,
        "id":165,
        "label":"API test field",
        "alias":"api_test_field11",
        "type":"text",
        "group":null,
        "order":36,
        "object":"lead",
        "defaultValue":null,
        "isRequired":false,
        "isPubliclyUpdatable":false,
        "isUniqueIdentifier":0,
        "properties":[]
      }
    }
    

    Get an individual field by ID.

    HTTP Request

    GET /fields/contact/ID or GET /fields/company/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Field Properties

    Name Type Description
    id int ID of the field
    isPublished bool Published state
    publishUp datetime/null Date/time when the field should be published
    publishDown datetime/null Date/time the field should be un published
    dateAdded datetime Date/time field was created
    createdBy int ID of the user that created the field
    createdByUser string Name of the user that created the field
    dateModified datetime/null Date/time field was last modified
    modifiedBy int ID of the user that last modified the field
    modifiedByUser string Name of the user that last modified the field
    label string Name of the field
    alias string Unique alias of the field used in the form field name attributes
    description string/null Description of the field
    type string Field type
    group string Groupd of the fields where the field belongs
    order int Order number of the field
    object string Which object use the field. Contact (lead) or Company.
    defaultValue string Default value of the field.
    isRequired boolean True if the field is required.
    isPubliclyUpdatable boolean True if the field value can be changed from public requests. The tracking pixel query for example.
    isUniqueIdentifier boolean True if the field is unique identifier and so the contacts should merge if the value of this field is the same.
    properties array Field options if the field type needs some.

    List Contact Fields

    <?php
    
    //...
    $fields = $fieldApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
      "total":71,
      "fields":[  
        {  
          "isPublished":true,
          "dateAdded":"2016-10-12T11:31:13+00:00",
          "createdBy":1,
          "createdByUser":"John Doe",
          "dateModified":"2016-10-12T11:31:30+00:00",
          "modifiedBy":1,
          "modifiedByUser":"John Doe",
          "id":100,
          "label":"Multiselect test",
          "alias":"multiselect_test",
          "type":"multiselect",
          "group":"core",
          "order":3,
          "object":"lead",
          "defaultValue":null,
          "isRequired":false,
          "isPubliclyUpdatable":false,
          "isUniqueIdentifier":false,
          "properties":{  
            "list":[  
              {  
                "label":"PHP",
                "value":"php"
              },
              {  
                "label":"JS",
                "value":"js"
              },
              {  
                "label":"English",
                "value":"en"
              }
            ]
          }
        },
        [...]
      ]
    }
    

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    HTTP Request

    GET /fields/contact or GET /fields/company

    Response

    Expected Response Code: 200

    See JSON code example.

    Field Properties

    Name Type Description
    id int ID of the field
    isPublished bool Published state
    publishUp datetime/null Date/time when the field should be published
    publishDown datetime/null Date/time the field should be un published
    dateAdded datetime Date/time field was created
    createdBy int ID of the user that created the field
    createdByUser string Name of the user that created the field
    dateModified datetime/null Date/time field was last modified
    modifiedBy int ID of the user that last modified the field
    modifiedByUser string Name of the user that last modified the field
    label string Name of the field
    alias string Unique alias of the field used in the form field name attributes
    description string/null Description of the field
    type string Field type
    group string Groupd of the fields where the field belongs
    order int Order number of the field
    object string Which object use the field. Contact (lead) or Company.
    defaultValue string Default value of the field.
    isRequired boolean True if the field is required.
    isPubliclyUpdatable boolean True if the field value can be changed from public requests. The tracking pixel query for example.
    isUniqueIdentifier boolean True if the field is unique identifier and so the contacts should merge if the value of this field is the same.
    properties array Field options if the field type needs some.

    Create Field

    <?php 
    
    $data = array(
        'label' => 'API test field',
        'type' => 'text',
    );
    
    $field = $fieldApi->create($data);
    

    Multiselect Field ```php <?php

    $data = array( 'label' => 'API test field', 'type' => 'multiselect', 'isPubliclyUpdatable' => true, 'properties' => array( 'list' => array( array( 'label' => 'label 1', 'value' => 'value 1' ), array( 'label' => 'label 2', 'value' => 'value 2' ) ) ) );

    $field = $fieldApi->create($data);

    Create a new field.

    HTTP Request

    POST /fields/contact/new or POST /fields/company/new

    Post Parameters

    Name Description
    label string
    alias string
    description string/null
    type string
    group string
    order int
    object string
    defaultValue string
    isRequired boolean
    isPubliclyUpdatable boolean
    isUniqueIdentifier boolean
    properties array

    Response

    Expected Response Code: 201

    Properties

    Same as Get Field.

    Edit Field

    <?php
    
    $id   = 1;
    $data = array(
        'label' => 'API test field',
        'type' => 'text',
    );
    
    // Create new a field of ID 1 is not found?
    $createIfNotFound = true;
    
    $field = $fieldApi->edit($id, $data, $createIfNotFound);
    

    Edit a new field. Field that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a field if the given ID does not exist and clears all the field infieldation, adds the infieldation from the request. PATCH fails if the field with the given ID does not exist and updates the field field values with the values field the request.

    HTTP Request

    To edit a field and return a 404 if the field is not found:

    PATCH /fields/contact/ID/edit or PATCH /fields/company/ID/edit

    To edit a field and create a new one if the field is not found:

    PUT /fields/contact/ID/edit or PUT /fields/company/ID/edit

    Post Parameters

    Name Description
    label string
    alias string
    description string/null
    type string
    group string
    order int
    object string
    defaultValue string
    isRequired boolean
    isPubliclyUpdatable boolean
    isUniqueIdentifier boolean
    properties array

    Response

    If PUT, the expected response code is 200 if the field was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Field.

    Delete Field

    <?php
    
    $field = $fieldApi->delete($id);
    

    Delete a field.

    HTTP Request

    DELETE /fields/contact/ID/delete or DELETE /fields/company/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Field.

    Files

    This endpoint is useful for working with files of images and assets.

    Note: Assets doesn't have nor support subdirectories.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $filesApi = $api->newApi("files", $auth, $apiUrl);
    

    Get List of files

    <?php
    
    // Get list of root media/images directory:
    $files = $filesApi->getList();
    
    // Get list of some sub-directory (flags in this case) of media/images:
    $filesApi->setFolder('images/flags');
    $files = $filesApi->getList();
    
    // Get list of root media/files directory where the asset files are stored:
    $files = $filesApi->setFolder('assets');
    $files = $filesApi->getList();
    
    {  
      "files":{  
        "3":"0b0f20185251d1c0cd5ff17950213fc9.png",
        "4":"0f530efdf837d3005bd2ab81cc30e878.jpeg",
        "5":"162a694f4101cb06c27c0a0699bd87c4.png",
        "6":"16ada2e2ecfa3f1d8cbb5d633f0bd8c6.png",
        ...
      }
    }
    

    HTTP Request

    GET /files/images to get root images directory GET /files/images?subdir=flags to get images/flags directory GET /files/assets to get root assets directory

    Response

    Expected Response Code: 200

    See JSON code example.

    Response Properties

    Name Type Description
    files array List of requested files and directories

    Create File

    <?php
    $data = array(
        'file' => dirname(__DIR__).'/'.'mauticlogo.png' // Must be a path to an existing file
    );
    
    // Create a file in root media/images directory:
    $response = $fileApi->create($data);
    
    // Create a file in some sub-directory (flags in this case) of media/images:
    $filesApi->setFolder('images/flags');
    $response = $fileApi->create($data);
    
    // Create a file in media/files directory where the asset files are stored:
    $files = $filesApi->setFolder('assets');
    $response = $fileApi->create($data);
    

    Creates a file. The file is sent via regular POST files array like a browser sends it during file upload.

    HTTP Request

    POST /files/DIR/new

    Response

    Expected Response Code: 200 json { "file":{ "link":"http:\/\/yourmautic\/media\/images\/2b912b934dd2a4da49a226d0bf68bfea.png", "name":"2b912b934dd2a4da49a226d0bf68bfea.png" } }

    Response Properties

    Name Type Description
    link string Appears only for files in image directory, not for assets
    name string File name of newly created file

    Delete File

    <?php
    // Delete a file from root media/images directory:
    $response = $fileApi->delete($fileName);
    
    // Delete a file from some sub-directory (flags in this case) of media/images:
    $filesApi->setFolder('images/flags');
    $response = $fileApi->delete($fileName);
    
    // Delete a file from media/files directory where the asset files are stored:
    $files = $filesApi->setFolder('assets');
    $response = $fileApi->delete($fileName);
    

    Delete a file.

    HTTP Request

    DELETE /files/DIR/FILE/delete

    Response

    Expected Response Code: 200 json { "success": true }

    Forms

    Use this endpoint to obtain details on Mautic's forms.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $formApi  = $api->newApi("forms", $auth, $apiUrl);
    

    Get Form

    <?php
    
    //...
    $form = $formApi->get($id);
    
    {
        "form": {
            "id": 3,
            "name": "Newlsetter",
            "alias": "newsletter",
            "description": null,
            "isPublished": true,
            "publishUp": null,
            "publishDown": null,
            "dateAdded": "2015-07-15T15:06:02-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-20T13:11:56-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "category": null,
            "cachedHtml": "\n\n<script...",
            "template": null,
            "fields": {
                "26": {
                    "id": 26,
                    "label": "Email",
                    "showLabel": false,
                    "alias": "email",
                    "type": "text",
                    "defaultValue": null,
                    "isRequired": true,
                    "validationMessage": "Email is required",
                    "helpMessage": null,
                    "order": 1,
                    "properties": {
                        "placeholder": "Email address"
                    },
                    "labelAttributes": null,
                    "inputAttributes": null,
                    "containerAttributes": null
                },
                "27": {
                    "id": 27,
                    "label": "Submit",
                    "showLabel": true,
                    "alias": "submit",
                    "type": "button",
                    "defaultValue": null,
                    "isRequired": false,
                    "validationMessage": null,
                    "helpMessage": null,
                    "order": 4,
                    "properties": [],
                    "labelAttributes": null,
                    "inputAttributes": null,
                    "containerAttributes": null
                }
            },
            "actions": {
                "4": {
                    "id": 4,
                    "type": "email.send.lead",
                    "name": "Send thank you email",
                    "description": null,
                    "order": 1,
                    "properties": {
                        "email": 21
                    }
                }
            }
        }
    }
    

    Get an individual form by ID.

    HTTP Request

    GET /forms/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Form Properties

    Name Type Description
    id int ID of the form
    name string Name of the form
    description string/null Description of the form
    alias string Used to generate the URL for the form
    isPublished bool Published state
    publishUp datetime/null Date/time when the form should be published
    publishDown datetime/null Date/time the form should be un published
    dateAdded datetime Date/time form was created
    createdBy int ID of the user that created the form
    createdByUser string Name of the user that created the form
    dateModified datetime/null Date/time form was last modified
    modifiedBy int ID of the user that last modified the form
    modifiedByUser string Name of the user that last modified the form
    cachedHtml string Cached HTML for the form
    template string/null Name of the template used to generate the HTML
    fields array Array of Field entities for the form. See below.
    actions array Array of Action entities for the form. See below.

    Field Properties

    Name Type Description
    id int ID of the field
    label string Label of the field
    showLabel bool Display the label of the field
    alias string Alias of the field (used as the database column)
    type string Field type
    defaultValue string Default value
    isRequired bool Field is required
    validationMessage string Validation message if required field is left empty
    helpMessage string Help message for the field
    order int Order of the field
    properties array Configured properties for the field
    labelAttributes string/null Custom HTML attributes for the label
    inputAttributes Custom HTML attributes for the input
    containerAttributes Custom HTML attributes for the container

    Action Properties

    Name Type Description
    id int ID of the action
    type string Action type
    name string Name of the action
    description string/null Description of the action
    order int Action order
    properties array Configured properties for the action

    List Forms

    <?php
    // ...
    
    $forms = $formApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "forms": [
            {
                "id": 3,
                "name": "Newlsetter",
                "alias": "newsletter",
                "description": null,
                "isPublished": true,
                "publishUp": null,
                "publishDown": null,
                "dateAdded": "2015-07-15T15:06:02-05:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": "2015-07-20T13:11:56-05:00",
                "modifiedBy": 1,
                "modifiedByUser": "Joe Smith",
                "category": null,
                "cachedHtml": "\n\n<script...",
                "template": null,
                "fields": {
                    "26": {
                        "id": 26,
                        "label": "Email",
                        "showLabel": false,
                        "alias": "email",
                        "type": "text",
                        "defaultValue": null,
                        "isRequired": true,
                        "validationMessage": "Email is required",
                        "helpMessage": null,
                        "order": 1,
                        "properties": {
                            "placeholder": "Email address"
                        },
                        "labelAttributes": null,
                        "inputAttributes": null,
                        "containerAttributes": null
                    },
                    "27": {
                        "id": 27,
                        "label": "Submit",
                        "showLabel": true,
                        "alias": "submit",
                        "type": "button",
                        "defaultValue": null,
                        "isRequired": false,
                        "validationMessage": null,
                        "helpMessage": null,
                        "order": 4,
                        "properties": [],
                        "labelAttributes": null,
                        "inputAttributes": null,
                        "containerAttributes": null
                    }
                },
                "actions": {
                    "4": {
                        "id": 4,
                        "type": "email.send.lead",
                        "name": "Send thank you email",
                        "description": null,
                        "order": 1,
                        "properties": {
                            "email": 21
                        }
                    }
                }
            }
        ]
    }
    

    HTTP Request

    GET /forms

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Form.

    Create Form

    <?php
    
    $data = array(
        'name' => 'test',
        'formType' => 'standalone',
        'description' => 'API test',
        'fields' => array(
            array(
                'label' => 'field name',
                'type' => 'text'
            )
        ),
        'actions' => array(
            array(
                'name' => 'action name',
                'description' => 'action desc',
                'type' => 'lead.pointschange',
                'properties' => array(
                    'operator' => 'plus',
                    'points' => 2
                )
            )
        )
    );
    
    $form = $formApi->create($data);
    

    Create a new form.

    HTTP Request

    POST /forms/new

    Post Parameters

    Same as Get Form. Form fields and actions can be created/edited via the forms/actions arrays in the form array.

    Response

    Expected Response Code: 201

    Properties

    Same as Get Form.

    Edit Form

    <?php
    
    $id   = 1;
    $data = array(
        'name' => 'test',
        'formType' => 'standalone',
        'description' => 'API test',
        'fields' => array(
            array(
                'label' => 'A field that will be added',
                'type' => 'text'
            ),
            array(
                'id' => 1,
                'label' => 'A field that will be edited',
                'type' => 'text'
            )
        ),
        'actions' => array(
            array(
                'name' => 'action name',
                'description' => 'action desc',
                'type' => 'lead.pointschange',
                'properties' => array(
                    'operator' => 'plus',
                    'points' => 2
                )
            )
        )
    );
    
    // Create new a form of ID 1 is not found?
    $createIfNotFound = true;
    
    $form = $formApi->edit($id, $data, $createIfNotFound);
    

    Edit a new form. Note that this supports PUT or PATCH depending on the desired behavior.

    Make sure that whenever you want to edit a form field that you include the form field id in the request. Fields without an id are assumed to be new fields.

    PUT creates a form if the given ID does not exist and clears all the form information, adds the information from the request. Form fields and actions will be also deleted if not present in the request. PATCH fails if the form with the given ID does not exist and updates the form field values with the values form the request.

    HTTP Request

    To edit a form and return a 404 if the form is not found:

    PATCH /forms/ID/edit

    To edit a form and create a new one if the form is not found:

    PUT /forms/ID/edit

    Post Parameters

    Same as Get Form. Form fields and actions can be created/edited via the forms/actions arrays in the form array.

    Response

    If PUT, the expected response code is 200 if the form was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Form.

    Delete Form

    <?php
    
    $form = $formApi->delete($id);
    

    Delete a form.

    HTTP Request

    DELETE /forms/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Form.

    Delete Form Fields

    The following examples will show how to delete fields with ID 56 and 59.

    <?php
    
    $form = $formApi->deleteFields($formId, array(56, 59));
    

    Delete a form fields.

    HTTP Request

    DELETE /forms/ID/fields/delete?fields[]=56&fields[]=59

    Response

    Expected Response Code: 200

    Properties

    Same as Get Form.

    Delete Form Actions

    The following examples will show how to delete actions with ID 56 and 59.

    <?php
    
    $form = $formApi->deleteActions($formId, array(56, 59));
    

    Delete a form actions.

    HTTP Request

    DELETE /forms/ID/actions/delete?actions[]=56&actions[]=59

    Response

    Expected Response Code: 200

    Properties

    Same as Get Form.

    List Form Submissions

    <?php
    
    $submissions = $formApi->getSubmissions($formId, $searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
      "total": "1",
      "submissions": [
        {
          "id": 1,
          "ipAddress": {
            "ip": "127.0.0.1"
          },
          "form": {
            "id": 25,
            "name": "test",
            "alias": "test",
            "category": null
          },
          "lead": {
            "id": 2183,
            "points": 0,
            "color": null,
            "title": null,
            "firstname": null,
            "lastname": null,
            "company": null,
            "position": null,
            "email": "test@test.test",
            "phone": null,
            "mobile": null,
            "address1": null,
            "address2": null,
            "city": null,
            "state": null,
            "zipcode": null,
            "timezone": null,
            "country": null
          },
          "trackingId": null,
          "dateSubmitted": "2017-07-17T09:52:29+00:00",
          "referer": "http:\/\/mautic.dev\/s\/forms\/preview\/25",
          "page": null,
          "results": {
            "email": "test@test.test"
          }
        }
      ]
    }
    

    HTTP Request

    GET /forms/FORM_ID/submissions

    Query Parameters

    Name Description
    formId ID of the form you want to get submissions for
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response, also can use column of joined table with prefix. Sort by submitted date is s.date_submitted
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Name Type Description
    id int ID of the submission
    ipAddress array Associative array containing IP address of the client who made the submission
    form array Simplified associative array of the form containing id, name, alias and category
    lead array Associative array of the lead containing the core values as well as custom fields
    dateSubmitted string Date time string holding the UTC date and time when the submission was made
    referer string HTTP referer info
    results array Associative array of the form fields as the keys and submission values

    List Form Submissions for a contact

    <?php
    
    $submissions = $formApi->getSubmissionsForContact($formId, $contactId, $searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    

    HTTP Request

    GET /forms/FORM_ID/submissions/contact/CONTACT_ID

    Response and properties same as Get Form Submissions. Parameters too except the ContactId was added.

    Get Form Submission

    <?php
    
    //...
    $form = $formApi->getSubmission($formId, $submissionId);
    
    {
      "submission": {
        "id": 1,
        "ipAddress": {
          "ip": "127.0.0.1"
        },
        "form": {
          "id": 25,
          "name": "test",
          "alias": "test",
          "category": null
        },
        "lead": {
          "id": 2183,
          "points": 0,
          "color": null,
          "title": null,
          "firstname": null,
          "lastname": null,
          "company": null,
          "position": null,
          "email": "test@test.test",
          "phone": null,
          "mobile": null,
          "address1": null,
          "address2": null,
          "city": null,
          "state": null,
          "zipcode": null,
          "timezone": null,
          "country": null
        },
        "trackingId": null,
        "dateSubmitted": "2017-07-17T09:52:29+00:00",
        "referer": "http:\/\/mautic.dev\/s\/forms\/preview\/25",
        "page": null,
        "results": {
          "form_id": "25",
          "email": "test@test.test"
        }
      }
    }
    

    Get an individual form submission by ID.

    HTTP Request

    GET /forms/FORM_ID/submissions/SUBMISSION_ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Form Properties

    Same as Get Form Submissions.

    Marketing Messages

    Use this endpoint to obtain details, create, update or delete Mautic's messages.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $messageApi = $api->newApi("messages", $auth, $apiUrl);
    

    Get Marketing Message

    <?php
    
    //...
    $message = $messageApi->get($id);
    
    {
        "message": {
            "isPublished": true,
            "dateAdded": "2017-02-08T15:00:34+01:00",
            "dateModified": "2017-02-08T15:00:35+01:00",
            "createdBy": 1,
            "createdByUser": "John Doe",
            "modifiedBy": 1,
            "modifiedByUser": "John Doe",
            "id": 26,
            "name": "Thanks for the feedback!",
            "description": "",
            "publishUp": null,
            "publishDown": null,
            "channels": [
                {
                    "id": 55,
                    "channel": "email",
                    "channelId": 1197,
                    "channelName": "Email A",
                    "isEnabled": true
                },
                {
                    "id": 57,
                    "channel": "notification",
                    "channelId": null,
                    "channelName": null,
                    "isEnabled": false
                },
                {
                    "id": 56,
                    "channel": "sms",
                    "channelId": 103,
                    "channelName": "SMS A",
                    "isEnabled": false
                },
                {
                    "id": 91,
                    "channel": "tweet",
                    "channelId": null,
                    "channelName": null,
                    "isEnabled": false
                }
            ]
        }
    }
    

    Get an individual marketing message by ID.

    HTTP Request

    GET /messages/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Marketing Message Properties

    Name Type Description
    id int ID of the message
    name string Internal name of the message
    isPublished bool Published state
    publishUp datetime/null Date/time when the message should be published
    publishDown datetime/null Date/time the message should be un published
    dateAdded datetime Date/time message was created
    createdBy int ID of the user that created the message
    createdByUser string Name of the user that created the message
    dateModified datetime/null Date/time message was last modified
    modifiedBy int ID of the user that last modified the message
    modifiedByUser string Name of the user that last modified the message
    channels array Array of channels configured for the marketing message

    List Marketing Messages

    <?php
    // ...
    
    $messages = $messageApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "messages": {
            "1": {
                "isPublished": true,
                "dateAdded": "2017-02-03T16:51:58+00:00",
                "dateModified": "2017-02-03T19:11:41+00:00",
                "createdBy": 1,
                "createdByUser": "John Doe",
                "modifiedBy": 1,
                "modifiedByUser": "John Doe",
                "id": 1,
                "name": "Live long and prosper",
                "description": null,
                "publishUp": null,
                "publishDown": null,
                "channels": [
                    {
                        "id": 1,
                        "channel": "email",
                        "channelId": 44,
                        "channelName": "Email A",
                        "isEnabled": true
                    },
                    {
                        "id": 2,
                        "channel": "sms",
                        "channelId": 1,
                        "channelName": "SMS A",
                        "isEnabled": true
                    },
                    {
                        "id": 3,
                        "channel": "notification",
                        "channelId": 75,
                        "channelName": null,
                        "isEnabled": false
                    }
                ]
            }
        }
    }
    

    HTTP Request

    GET /messages

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Marketing Message.

    Create Marketing Message

    <?php 
    
    $data = array(
        'name'        => 'Marketing Message A',
        'description' => 'This is my first message created via API.',
        'isPublished' => 1,
        'channels' => array(
            'email' => array(
                'channel' => 'email',
                'channelId' => 44,
                'isEnabled' => true,
            ),
            'sms' => array(
                'channel' => 'sms',
                'channelId' => 1,
                'isEnabled' => true,
            ),
            'notification' => array(
                'channel' => 'notification',
                'channelId' => 75,
                'isEnabled' => false,
            )
        )
    );
    
    $message = $messageApi->create($data);
    

    Create a new message.

    HTTP Request

    POST /messages/new

    Post Parameters

    Name Type Description
    id int ID of the message
    name string Internal name of the message
    isPublished bool Published state
    publishUp datetime/null Date/time when the message should be published
    publishDown datetime/null Date/time the message should be un published
    channels array Array of channels

    Response

    Expected Response Code: 201

    Properties

    Same as Get Marketing Message.

    Edit Marketing Message

    <?php
    
    $id   = 1;
    $data = array(
        'name'        => 'New message title',
        'isPublished' => 0
    );
    
    // Create new a message of ID 1 is not found?
    $createIfNotFound = true;
    
    $message = $messageApi->edit($id, $data, $createIfNotFound);
    

    Edit a new message. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a message if the given ID does not exist and clears all the message information, adds the information from the request. PATCH fails if the message with the given ID does not exist and updates the message field values with the values form the request.

    HTTP Request

    To edit a message and return a 404 if the message is not found:

    PATCH /messages/ID/edit

    To edit a message and create a new one if the message is not found:

    PUT /messages/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the message
    name string Internal name of the message
    isPublished bool Published state
    publishUp datetime/null Date/time when the message should be published
    publishDown datetime/null Date/time the message should be un published
    channels array Array of channels

    Response

    If PUT, the expected response code is 200 if the message was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Marketing Message.

    Delete Marketing Message

    <?php
    
    $message = $messageApi->delete($id);
    

    Delete a message.

    HTTP Request

    DELETE /messages/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Marketing Message.

    Notes

    Use this endpoint to obtain details on Mautic's contact notes.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $noteApi  = $api->newApi("notes", $auth, $apiUrl);
    

    Get Note

    <?php
    
    //...
    $note = $noteApi->get($id);
    
    {  
      "note":{  
        "id":39,
        "text":"Contact note created via API request",
        "type":"general",
        "dateTime":null,
        "lead":{  
          "id":1405,
          "points":0,
          "color":null,
          "fields":{  
            "core":{  
              "firstname":{  
                "id":"2",
                "label":"First Name",
                "alias":"firstname",
                "type":"text",
                "group":"core",
                "field_order":"42",
                "object":"lead",
                "value":"Note API test"
              },
              "lastname":{  
                "id":"3",
                "label":"Last Name",
                "alias":"lastname",
                "type":"text",
                "group":"core",
                "field_order":"44",
                "object":"lead",
                "value":null
              },
              [...]
            },
          }
        }
      }
    }
    

    Get an individual note by ID.

    HTTP Request

    GET /notes/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Note Properties

    Name Type Description
    id int ID of the note
    lead array data of the contact
    text string Note text
    type string Note type
    datetime datetime Date and time related to the note.

    List Contact Notes

    <?php
    
    //...
    $notes = $noteApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
      "total":24,
      "notes":[  
        {  
          "id":1,
          "text":"A test note",
          "type":"general",
          "dateTime":"2016-06-14T18:07:00+00:00",
          "lead":{  
            "id":1,
            "points":0,
            "color":null,
            "fields":[]
          }
        },
        [...]
      ]
    }
    

    HTTP Request

    GET /notes

    Response

    Expected Response Code: 200

    See JSON code example.

    Note Properties

    Name Type Description
    id int ID of the note
    lead array data of the contact
    text string Note text
    type string Note type
    datetime datetime Date and time related to the note.

    Create Note

    <?php 
    
    $contactID = 1;
    
    $data = array(
        'lead' => $contactID,
        'text' => 'Note A',
        'type' => 'general',
    );
    
    $note = $noteApi->create($data);
    

    Create a new note.

    HTTP Request

    POST /notes/new

    Post Parameters

    Name Description
    text string
    type string
    datetime datetime

    Response

    Expected Response Code: 201

    Properties

    Same as Get Note.

    Edit Note

    <?php
    
    $id   = 1;
    $data = array(
        'text' => 'Note B',
        'type' => 'general',
    );
    
    // Create new a note of ID 1 is not found?
    $createIfNotFound = true;
    
    $note = $noteApi->edit($id, $data, $createIfNotFound);
    

    Edit a new note. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a note if the given ID does not exist and clears all the note information, adds the information from the request. PATCH fails if the note with the given ID does not exist and updates the note field values with the values form the request.

    HTTP Request

    To edit a note and return a 404 if the note is not found:

    PATCH /notes/ID/edit

    To edit a note and create a new one if the note is not found:

    PUT /notes/ID/edit

    Post Parameters

    Name Description
    text string
    type string
    datetime datetime

    Response

    If PUT, the expected response code is 200 if the note was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Note.

    Delete Note

    <?php
    
    $note = $noteApi->delete($id);
    

    Delete a note.

    HTTP Request

    DELETE /notes/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Note.

    Notifications

    Use this endpoint to obtain details on Mautic's notifications.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth        = new ApiAuth();
    $auth            = $initAuth->newAuth($settings);
    $apiUrl          = "https://your-mautic.com";
    $api             = new MauticApi();
    $notificationApi = $api->newApi("notifications", $auth, $apiUrl);
    

    Get Notification

    <?php
    
    //...
    $notification = $notificationApi->get($id);
    
    {  
        "notification":{  
            "isPublished":true,
            "dateAdded":"2016-09-14T14:03:05+00:00",
            "createdBy":1,
            "createdByUser":"John Doe",
            "dateModified":"2016-09-15T08:40:46+00:00",
            "modifiedBy":1,
            "modifiedByUser":"John Doe",
            "id":1,
            "name":"The first notification",
            "heading":"The first notification Heading",
            "message":"The first notification Message",
            "url":"http:\/\/mautic.org",
            "language":"en",
            "category":null,
            "publishUp":null,
            "publishDown":null,
            "readCount":0,
            "sentCount":0
        }
    }
    

    Get an individual notification by ID.

    HTTP Request

    GET /notifications/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Notification Properties

    Name Type Description
    id int ID of the notification
    name string Title of the notification
    heading string Heading of the notification
    message string Message of the notification
    url string URL to go to when the notification is clicked
    isPublished bool Published state
    publishUp datetime/null Date/time when the notification should be published
    publishDown datetime/null Date/time the notification should be un published
    dateAdded datetime Date/time notification was created
    createdBy int ID of the user that created the notification
    createdByUser string Name of the user that created the notification
    dateModified datetime/null Date/time notification was last modified
    modifiedBy int ID of the user that last modified the notification
    modifiedByUser string Name of the user that last modified the notification
    language string Language locale of the notification
    readCount int Total notification read count
    sentCount int Unique notification sent count
    category null/object Category

    List Notifications

    <?php
    // ...
    
    $notifications = $notificationApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
        "total":1,
        "notifications":[  
            {  
                "isPublished":true,
                "dateAdded":"2016-09-14T14:03:05+00:00",
                "createdBy":1,
                "createdByUser":"John Doe",
                "dateModified":"2016-09-15T08:40:46+00:00",
                "modifiedBy":1,
                "modifiedByUser":"John Doe",
                "id":1,
                "name":"The first notification",
                "heading":"The first notification Heading",
                "message":"The first notification Message",
                "url":"http:\/\/mautic.org",
                "language":"en",
                "category":null,
                "publishUp":null,
                "publishDown":null,
                "readCount":0,
                "sentCount":0
            }
        ]
    }
    

    HTTP Request

    GET /notifications

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Notification.

    Create Notification

    <?php 
    
    $data = array(
        'name'    => 'Notification A',
        'heading' => 'Hello World!'
        'message' => 'This is my first notification created via API.',
    );
    
    $notification = $notificationApi->create($data);
    

    Create a new notification.

    HTTP Request

    POST /notifications/new

    Post Parameters

    Name Type Description
    id int ID of the notification
    name string Title of the notification
    heading string Heading of the notification
    message string Message of the notification
    url string URL to go to when the notification is clicked
    isPublished bool Published state
    publishUp datetime/null Date/time when the notification should be published
    publishDown datetime/null Date/time the notification should be un published
    language string Language locale of the notification

    Response

    Expected Response Code: 201

    Properties

    Same as Get Notification.

    Edit Notification

    <?php
    
    $id   = 1;
    $data = array(
        'name'    => 'Notification A',
        'heading' => 'Hello World!'
        'message' => 'This is my first notification created via API.',
    );
    
    // Create new a notification of ID 1 is not found?
    $createIfNotFound = true;
    
    $notification = $notificationApi->edit($id, $data, $createIfNotFound);
    

    Edit a new notification. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a notification if the given ID does not exist and clears all the notification information, adds the information from the request. PATCH fails if the notification with the given ID does not exist and updates the notification field values with the values form the request.

    HTTP Request

    To edit a notification and return a 404 if the notification is not found:

    PATCH /notifications/ID/edit

    To edit a notification and create a new one if the notification is not found:

    PUT /notifications/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the notification
    name string Title of the notification
    heading string Heading of the notification
    message string Message of the notification
    url string URL to go to when the notification is clicked
    isPublished bool Published state
    publishUp datetime/null Date/time when the notification should be published
    publishDown datetime/null Date/time the notification should be un published
    language string Language locale of the notification

    Response

    If PUT, the expected response code is 200 if the notification was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Notification.

    Delete Notification

    <?php
    
    $notification = $notificationApi->delete($id);
    

    Delete a notification.

    HTTP Request

    DELETE /notifications/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Notification.

    Pages

    Use this endpoint to obtain details on Mautic's landing pages.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $pageApi  = $api->newApi("pages", $auth, $apiUrl);
    

    Get Page

    <?php
    
    //...
    $page = $pageApi->get($id);
    
    {
        "page": {
            "id": 3,
            "title": "Webinar Landing Page",
            "description": null,
            "isPublished": true,
            "publishUp": null,
            "publishDown": null,
            "dateAdded": "2015-07-15T15:06:02-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-20T13:11:56-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "category": "Events",
            "language": "en",
            "template": "blank",
            "customHtml": "<!DOCTYPE ...",
            "hits": 0,
            "uniqueHits": 0,
            "variantHits": 0,
            "revision": 1,
            "metaDescription": null,
            "redirectType": null,
            "redirectUrl": null,
            "translationChildren": [],
            "translationParent": null,
            "variantChildren": [],
            "variantParent": null,
            "variantSettings": [],
            "variantStartDate": null
        }
    }
    

    Get an individual page by ID.

    HTTP Request

    GET /pages/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Page Properties

    Name Type Description
    id int ID of the page
    title string Title of the page
    description string/null Description of the page
    alias string Used to generate the URL for the page
    isPublished bool Published state
    publishUp datetime/null Date/time when the page should be published
    publishDown datetime/null Date/time the page should be un published
    dateAdded datetime Date/time page was created
    createdBy int ID of the user that created the page
    createdByUser string Name of the user that created the page
    dateModified datetime/null Date/time page was last modified
    modifiedBy int ID of the user that last modified the page
    modifiedByUser string Name of the user that last modified the page
    language string Language locale of the page
    template string Template of the page
    customHtml string Static HTML of the page
    hits int Total page hit count
    uniqueHits int Unique page hit count
    revision int Page revision
    metaDescription Meta description for the page's
    redirectType int If unpublished, redirect with 301 or 302
    redirectUrl string If unpublished, the URL to redirect to if redirectType is set
    translationChildren array Array of Page entities for translations of this landing page
    translationParent object The parent/main page if this is a translation
    variantHits Hit count since variantStartDate
    variantChildren array Array of Page entities for variants of this landing page
    variantParent object The parent/main page if this is a variant (A/B test)
    variantSettings array The properties of the A/B test
    variantStartDate datetime/null The date/time the A/B test began

    List Pages

    <?php
    // ...
    
    $pages = $pageApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "pages": [
            {
                "id": 3,
                "title": "Webinar Landing Page",
                "description": null,
                "isPublished": true,
                "publishUp": null,
                "publishDown": null,
                "dateAdded": "2015-07-15T15:06:02-05:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": "2015-07-20T13:11:56-05:00",
                "modifiedBy": 1,
                "modifiedByUser": "Joe Smith",
                "category": "Events",
                "language": "en",
                "template": "blank",
                "hits": 0,
                "uniqueHits": 0,
                "variantHits": 0,
                "revision": 1,
                "metaDescription": null,
                "redirectType": null,
                "redirectUrl": null,
                "translationChildren": [],
                "translationParent": null,
                "variantChildren": [],
                "variantParent": null,
                "variantSettings": [],
                "variantStartDate": null
            }
        ]
    }
    

    HTTP Request

    GET /pages

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Page.

    Create Page

    <?php
    
    $data = array(
        'title'        => 'Page A',
        'description' => 'This is my first page created via API.',
        'isPublished' => 1
    );
    
    $page = $pageApi->create($data);
    

    Create a new page.

    HTTP Request

    POST /pages/new

    Post Parameters

    Name Description
    title Page title is the only required field
    alias string
    description A description of the page.
    isPublished A value of 0 or 1
    language string
    metaDescription Meta description for the page's
    redirectType int
    redirectUrl string

    Response

    Expected Response Code: 201

    Properties

    Same as Get Page.

    Edit Page

    <?php
    
    $id   = 1;
    $data = array(
        'title'        => 'New page title',
        'isPublished' => 0
    );
    
    // Create new a page of ID 1 is not found?
    $createIfNotFound = true;
    
    $page = $pageApi->edit($id, $data, $createIfNotFound);
    

    Edit a new page. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a page if the given ID does not exist and clears all the page information, adds the information from the request. PATCH fails if the page with the given ID does not exist and updates the page field values with the values form the request.

    HTTP Request

    To edit a page and return a 404 if the page is not found:

    PATCH /pages/ID/edit

    To edit a page and create a new one if the page is not found:

    PUT /pages/ID/edit

    Post Parameters

    Name Description
    title Page title is the only required field
    alias Name alias generated automatically if not set
    description A description of the page.
    isPublished A value of 0 or 1
    language string
    metaDescription Meta description for the page's
    redirectType int
    redirectUrl string

    Response

    If PUT, the expected response code is 200 if the page was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Page.

    Delete Page

    <?php
    
    $page = $pageApi->delete($id);
    

    Delete a page.

    HTTP Request

    DELETE /pages/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Page.

    Point Actions

    Use this endpoint to obtain details on Mautic's point actions.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $pointApi = $api->newApi("points", $auth, $apiUrl);
    

    Get Point Action

    <?php
    
    //...
    $point = $pointApi->get($id);
    
    {
        "point": {
            "id": 1,
            "name": "Opens Email",
            "description": null,
            "type": "email.send",
            "isPublished": true,
            "publishUp": null,
            "publishDown": null,
            "dateAdded": "2015-07-19T00:34:11-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-19T00:41:44-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "delta": 10,
            "properties": {
                "emails": [
                    35
                ]
            },
            "category": null
        }
    }
    

    Get an individual point action by ID.

    HTTP Request

    GET /points/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Point Action Properties

    Name Type Description
    id int ID of the point
    name string Name of the point
    description string/null Description of the point
    category string Category name
    type string Point action type
    isPublished bool Published state
    publishUp datetime/null Date/time when the point should be published
    publishDown datetime/null Date/time the point should be un published
    dateAdded datetime Date/time point was created
    createdBy int ID of the user that created the point
    createdByUser string Name of the user that created the point
    dateModified datetime/null Date/time point was last modified
    modifiedBy int ID of the user that last modified the point
    modifiedByUser string Name of the user that last modified the point
    delta int The number of points to give the lead when executing this action
    properties array Configured properties for this point action

    List Point Actions

    <?php
    // ...
    
    $points = $pointApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "points": [
            {
                "id": 1,
                "name": "Opens Email",
                "description": null,
                "category": null
                "type": "email.send",
                "isPublished": true,
                "publishUp": null,
                "publishDown": null,
                "dateAdded": "2015-07-19T00:34:11-05:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": "2015-07-19T00:41:44-05:00",
                "modifiedBy": 1,
                "modifiedByUser": "Joe Smith",
                "delta": 10,
                "properties": {
                    "emails": [
                        35
                    ]
                }
            }
        ]
    }
    

    HTTP Request

    GET /points

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Point Action.

    Create Point Action

    <?php 
    
    $data = array(
        'name' => 'test',
        'delta' => 5,
        'type' => 'page.hit',
        'description' => 'created as a API test'
    );
    
    $point = $pointApi->create($data);
    

    Create a new point action.

    HTTP Request

    POST /points/new

    Post Parameters

    Same as Get Point Action. Point Action fields and actions can be created/edited via the point actions/actions arrays in the point action array.

    Response

    Expected Response Code: 201

    Properties

    Same as Get Point Action.

    Edit Point Action

    <?php
    
    $id   = 1;
    $data = array(
        'name' => 'test',
        'delta' => 5,
        'type' => 'page.hit',
        'description' => 'created as a API test'
    );
    
    // Create new a point action of ID 1 is not found?
    $createIfNotFound = true;
    
    $point = $pointApi->edit($id, $data, $createIfNotFound);
    

    Edit a new point action. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a point action if the given ID does not exist and clears all the point action inpoint actionation, adds the inpoint actionation from the request. Point Action fields and actions will be also deleted if not present in the request. PATCH fails if the point action with the given ID does not exist and updates the point action field values with the values point action the request.

    HTTP Request

    To edit a point action and return a 404 if the point action is not found:

    PATCH /points/ID/edit

    To edit a point action and create a new one if the point action is not found:

    PUT /points/ID/edit

    Post Parameters

    Same as Get Point Action. Point Action fields and actions can be created/edited via the point actions/actions arrays in the point action array.

    Response

    If PUT, the expected response code is 200 if the point action was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Point Action.

    Delete Point Action

    <?php
    
    $point = $pointApi->delete($id);
    

    Delete a point action.

    HTTP Request

    DELETE /points/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Point Action.

    Get Point Action Types

    <?php
    
    $point = $pointApi->getPointActionTypes();
    

    Get array of available Point Action Types

    HTTP Request

    GET /points/actions/types

    Response

    Expected Response Code: 200

    {  
        "pointActionTypes":{  
            "asset.download":"Downloads an asset",
            "email.send":"Is sent an email",
            "email.open":"Opens an email",
            "form.submit":"Submits a form",
            "page.hit":"Visits a landing page",
            "url.hit":"Visits specific URL"
        }
    }
    

    See JSON code example.

    Point Triggers

    Use this endpoint to obtain details on Mautic's point triggers.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth   = new ApiAuth();
    $auth       = $initAuth->newAuth($settings);
    $apiUrl     = "https://your-mautic.com";
    $api        = new MauticApi();
    $triggerApi = $api->newApi("pointTriggers", $auth, $apiUrl);
    

    Get Point Trigger

    <?php
    
    //...
    $trigger = $triggerApi->get($id);
    
    {
        "trigger": {
             "id": 1,
             "name": "Trigger test",
             "description": null,
             "category": null,      
             "isPublished": true,      
             "publishUp": null,
             "publishDown": null,
             "dateAdded": "2015-07-23T03:20:42-05:00",
             "createdBy": 1,
             "createdByUser": "Joe Smith",
             "dateModified": null,
             "modifiedBy": null,
             "modifiedByUser": null,l,
             "points": 10,
             "color": "ab5959",
             "events": {
                 "1": {
                     "id": 1,
                     "type": "email.send",
                     "name": "Send email",
                     "description": null,
                     "order": 1,
                     "properties": {
                        "email": 21
                     }
                 }
             }
         }
    }
    

    Get an individual point trigger by ID.

    HTTP Request

    GET /points/triggers/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Point Trigger Properties

    Name Type Description
    id int ID of the point
    name string Name of the point
    description string/null Description of the point
    category string Category name
    isPublished bool Published state
    publishUp datetime/null Date/time when the point should be published
    publishDown datetime/null Date/time the point should be un published
    dateAdded datetime Date/time point was created
    createdBy int ID of the user that created the point
    createdByUser string Name of the user that created the point
    dateModified datetime/null Date/time point was last modified
    modifiedBy int ID of the user that last modified the point
    modifiedByUser string Name of the user that last modified the point
    points int The minimum number of points before the trigger events are executed
    color string Color hex to highlight the lead with. This value does NOT include the pound sign (#)
    events array Array of TriggerEvent entities for this trigger. See below.

    Trigger Event Properties

    Name Type Description
    id int ID of the event
    type string Event type
    name string Name of the event
    description string Description of the event
    order int Event order
    properties array Configured properties for the event

    List Point Triggers

    <?php
    // ...
    
    $triggers = $triggerApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
        "total": 1,
        "triggers": [
            {
                "id": 1,
                "name": "Trigger test",
                "description": null,
                "category": null,      
                "isPublished": true,      
                "publishUp": null,
                "publishDown": null,
                "dateAdded": "2015-07-23T03:20:42-05:00",
                "createdBy": 1,
                "createdByUser": "Joe Smith",
                "dateModified": null,
                "modifiedBy": null,
                "modifiedByUser": null,l,
                "points": 10,
                "color": "ab5959",
                "events": {
                    "1": {
                        "id": 1,
                        "type": "email.send",
                        "name": "Send email",
                        "description": null,
                        "order": 1,
                        "properties": {
                            "email": 21
                        }
                    }
                }
            }
        ]
    }
    

    HTTP Request

    GET /points/triggers

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Point Trigger.

    Create Point Trigger

    <?php 
    
    $data = array(
        'name' => 'test',
        'description' => 'created as a API test',
        'points' => 5,
        'color' => '4e5d9d',
        'trigger_existing_leads' => false,
        'events' => array(
            array(
                'name' => 'tag test event',
                'description' => 'created as a API test',
                'type' => 'lead.changetags',
                'order' => 1,
                'properties' => array(
                    'add_tags' => array('tag-a'),
                    'remove_tags' => array()
                )
            ),
            array(
                'name' => 'send email test event',
                'description' => 'created as a API test',
                'type' => 'email.send',
                'order' => 2,
                'properties' => array(
                    'email' => 1
                )
            )
        )
    );
    
    $trigger = $triggerApi->create($data);
    

    Create a new point trigger.

    HTTP Request

    POST /points/triggers/new

    Post Parameters

    Same as Get Point Trigger. Point Trigger events can be created/edited via the point trigger event arrays placed in the point trigger array.

    Response

    Expected Response Code: 201

    Properties

    Same as Get Point Trigger.

    Edit Point Trigger

    <?php
    
    $id   = 1;
    $data = array(
        'name' => 'test',
        'description' => 'created as a API test',
        'points' => 5,
        'color' => '4e5d9d',
        'trigger_existing_leads' => false,
        'events' => array(
            array(
                'name' => 'tag test event',
                'description' => 'created as a API test',
                'type' => 'lead.changetags',
                'order' => 1,
                'properties' => array(
                    'add_tags' => array('tag-a'),
                    'remove_tags' => array()
                )
            ),
            array(
                'name' => 'send email test event',
                'description' => 'created as a API test',
                'type' => 'email.send',
                'order' => 2,
                'properties' => array(
                    'email' => 1
                )
            )
        )
    );
    
    // Create new a point trigger of ID 1 is not found?
    $createIfNotFound = true;
    
    $trigger = $triggerApi->edit($id, $data, $createIfNotFound);
    

    Edit a new point trigger. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a point trigger if the given ID does not exist and clears all the point trigger information, adds the information from the request. Point Trigger events will be also deleted if not present in the request. PATCH fails if the point trigger with the given ID does not exist and updates the point trigger field values with the values point trigger the request.

    HTTP Request

    To edit a point trigger and return a 404 if the point trigger is not found:

    PATCH /points/triggers/ID/edit

    To edit a point trigger and create a new one if the point trigger is not found:

    PUT /points/triggers/ID/edit

    Post Parameters

    Same as Get Point Trigger. Point Trigger events can be created/edited via the point triggers event arrays placed in the point trigger array.

    Response

    If PUT, the expected response code is 200 if the point trigger was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Point Trigger.

    Delete Point Trigger

    <?php
    
    $trigger = $triggerApi->delete($id);
    

    Delete a point trigger.

    HTTP Request

    DELETE /points/triggers/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Point Trigger.

    Delete Point Trigger Events

    The following examples will show how to delete events with ID 56 and 59.

    <?php
    
    $trigger = $triggerApi->deleteFields($triggerId, array(56, 59));
    

    Delete a point trigger events.

    HTTP Request

    DELETE /points/triggers/ID/events/delete?events[]=56&events[]=59

    Response

    Expected Response Code: 200

    Properties

    Same as Get Point Trigger.

    Get Point Trigger Event Types

    <?php
    
    $point = $pointApi->getEventTypes();
    

    Get array of available Point Trigger Event Types

    HTTP Request

    GET /points/triggers/events/types

    Response

    Expected Response Code: 200

    {  
        "eventTypes":{  
            "campaign.changecampaign":"Modify contact's campaigns",
            "lead.changelists":"Modify contact's segments",
            "lead.changetags":"Modify contact's tags",
            "plugin.leadpush":"Push contact to integration",
            "email.send":"Send an email"
        }
    }
    

    Reports

    Use this endpoint to obtain details on Mautic's reports.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth  = new ApiAuth();
    $auth      = $initAuth->newAuth($settings);
    $apiUrl    = "https://your-mautic.com";
    $api       = new MauticApi();
    $reportApi = $api->newApi("reports", $auth, $apiUrl);
    

    Get Report

    <?php
    
    //...
    // Simple get all with default options:
    $report = $reportApi->get($id);
    
    // Or define exactly what rows you want:
    $limit    = 100;
    $page     = 2;
    $dateFrom = \DateTime('1 week ago');
    $dateTo   = \DateTime('now');
    $report   = $reportApi->get($id, $limit, $page, $dateFrom, $dateTo);
    
    {
      "totalResults": 3990,
      "data": [
        {
          "id2": "12",
          "email1": "john@doe.email",
          "firstname1": "",
          "lastname1": ""
        },
        {
          "id2": "23",
          "email1": "johnatan@doe.email",
          "firstname1": "",
          "lastname1": ""
        },
        {
          "id2": "24",
          "email1": "johny@doe.email",
          "firstname1": "",
          "lastname1": ""
        },
        {
          "id2": "25",
          "email1": "johan@doe.email",
          "firstname1": "",
          "lastname1": ""
        },
        {
          "id2": "26",
          "email1": "jane@doe.email",
          "firstname1": "",
          "lastname1": ""
        }
      ],
      "dataColumns": {
        "address11": "l.address1",
        "address21": "l.address2",
        "attribution1": "l.attribution",
        "attribution_date1": "l.attribution_date",
        "city1": "l.city",
        "company1": "l.company",
        "companyaddress11": "comp.companyaddress1",
        "companyaddress21": "comp.companyaddress2",
        "companycity1": "comp.companycity",
        "companyemail1": "comp.companyemail",
        "companyname1": "comp.companyname",
        "companycountry1": "comp.companycountry",
        "companydescription1": "comp.companydescription",
        "companyfax1": "comp.companyfax",
        "id1": "comp.id",
        "companyphone1": "comp.companyphone",
        "companystate1": "comp.companystate",
        "companywebsite1": "comp.companywebsite",
        "companyzipcode1": "comp.companyzipcode",
        "id2": "l.id",
        "country1": "l.country",
        "custom_select1": "l.custom_select",
        "date_identified1": "l.date_identified",
        "email1": "l.email",
        "facebook1": "l.facebook",
        "fax1": "l.fax",
        "firstname1": "l.firstname",
        "foursquare1": "l.foursquare",
        "gender1": "l.gender",
        "googleplus1": "l.googleplus",
        "ip_address1": "i.ip_address",
        "instagram1": "l.instagram",
        "is_primary1": "companies_lead.is_primary",
        "lastname1": "l.lastname",
        "linkedin1": "l.linkedin",
        "mobile1": "l.mobile",
        "multiline1": "l.multiline",
        "multiselect1": "l.multiselect",
        "owner_id1": "l.owner_id",
        "first_name1": "u.first_name",
        "last_name1": "u.last_name",
        "phone1": "l.phone",
        "points1": "l.points",
        "position1": "l.position",
        "preferred_locale1": "l.preferred_locale",
        "timezone1": "l.timezone",
        "skype1": "l.skype",
        "state1": "l.state",
        "title1": "l.title",
        "twitter1": "l.twitter",
        "website1": "l.website",
        "zipcode1": "l.zipcode",
      },
      "limit": 5,
      "page": 3,
      "dateFrom": "2017-01-01T00:00:00+00:00",
      "dateTo": "2018-10-24T11:55:29+00:00",
    }
    

    Get an individual report by ID.

    HTTP Request

    GET /reports/ID

    Or define query params like this:

    GET /reports/3?dateFrom=2017-01-01&dateTo=2018-01-01&limit=5&page=3

    Response

    Expected Response Code: 200

    See JSON code example.

    Report Properties

    Name Type Description
    totalResults int Amount of results in the defined date range. Default date range is from 30 days ago to now
    data array Holds rows of the report specific to each report data type and selected columns
    dataColumns array Array of supported column names for the report data type
    limit int Currently applied limit
    page int Currently applied page
    dateFrom datetime Currently applied date from filter
    dateTo datetime Currently applied date to filter

    List Reports

    <?php
    
    //...
    $reports = $reportApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
      "total":8,
      "reports":[  
        {  
          "id":1,
          "name":"Contacts",
          "descriptionn":"lists all contacts",
          "system": false,
          "isScheduled": false,
          "source": "leads",
          "columns": [
            "l.id",
            "l.email",
            "l.firstname",
            "l.lastname"
          ],
          "filters": [],
          "tableOrder": [],
          "graphs": [],
          "groupBy": [],
          "settings": {
            "showGraphsAboveTable": 0,
            "showDynamicFilters": 0,
            "hideDateRangeFilter": 0
          },
          "aggregators": [],
          "scheduleUnit": null,
          "toAddress": null,
          "scheduleDay": null,
          "scheduleMonthFrequency": null
        },
        [...]
      ]
    }
    

    Returns a list of contact reports available to the user. This list is not filterable.

    HTTP Request

    GET /reports

    Response

    Expected Response Code: 200

    See JSON code example.

    Report Properties

    Name Type Description
    id int ID of the report
    name string The report name
    description string The report description
    system boolean If true then the report is visible to all users. If false then only creator can see this report
    isScheduled boolean Scheduled reports send report emails as the user defines
    source string Report data source type
    columns array List of selected columns for this particular report
    filters array Filters applied on this report
    tableOrder array Ordering applied on this report
    graphs array Graphs defined for this report. API won't return graphs
    groupBy array Group by rules applied for this report
    settings array Additional settings for the UI layout
    aggregators array Aggregation rules applied on this report
    scheduleUnit string or null Unit for the scheduler
    toAddress string or null Email address for the scheduler
    scheduleDay string or null Day for the scheduler
    scheduleMonthFrequency string or null Frequency for the scheduler

    Roles

    Use this endpoint to obtain details on Mautic's roles (administrators).

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $roleApi  = $api->newApi("roles", $auth, $apiUrl);
    

    Get Role

    <?php
    
    //...
    $role = $roleApi->get($id);
    
    {  
      "role":{  
        "isPublished":true,
        "dateAdded":"2016-11-09T15:24:32+00:00",
        "createdBy":1,
        "createdByUser":"John Doe",
        "dateModified":null,
        "modifiedBy":null,
        "modifiedByUser":null,
        "id":13,
        "name":"API test role",
        "description":"created via AIP",
        "isAdmin":false,
        "rawPermissions":{  
          "email:emails":[  
            "viewown",
            "viewother"
          ]
        }
      }
    }
    

    Get an individual role by ID.

    HTTP Request

    GET /roles/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Role Properties

    Name Type Description
    id int ID of the contact
    dateAdded datetime Date/time contact was created
    createdBy int ID of the role that created the contact
    createdByRole string Name of the role that created the contact
    dateModified datetime/null Date/time contact was last modified
    modifiedBy int ID of the role that last modified the contact
    modifiedByRole string Name of the role that last modified the contact
    name string Name of the role
    description string Description of the role
    isAdmin boolean Whether the role has full access or only some
    rawPermissions array List of roles

    List Contact Roles

    <?php
    
    //...
    $roles = $roleApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
      "total":9,
      "roles":[  
        {  
          "isPublished":true,
          "dateAdded":"2016-08-01T11:51:32+00:00",
          "createdBy":1,
          "createdByUser":"John Doe",
          "dateModified":null,
          "modifiedBy":null,
          "modifiedByUser":null,
          "id":2,
          "name":"view email",
          "description":null,
          "isAdmin":false,
          "rawPermissions":{  
            "email:emails":[  
              "viewown",
              "viewother"
            ]
          }
        },
        [...]
      ]
    }
    

    HTTP Request

    GET /roles

    Response

    Expected Response Code: 200

    See JSON code example.

    Role Properties

    Name Type Description
    id int ID of the contact
    dateAdded datetime Date/time contact was created
    createdBy int ID of the role that created the contact
    createdByRole string Name of the role that created the contact
    dateModified datetime/null Date/time contact was last modified
    modifiedBy int ID of the role that last modified the contact
    modifiedByRole string Name of the role that last modified the contact
    name string Name of the role
    description string Description of the role
    isAdmin boolean Whether the role has full access or only some
    rawPermissions array List of roles

    Create Role

    <?php 
    
    $data = array(
        'name' => 'API test role',
        'description' => 'created via AIP',
        'rawPermissions' => array (
            'email:emails' => 
            array (
                'viewown',
                'viewother',
            ),
        )
    );
    
    $role = $roleApi->create($data);
    

    Create a new role.

    HTTP Request

    POST /roles/new

    Post Parameters

    Name Description
    name string
    description string
    isAdmin boolean
    rawPermissions array

    Response

    Expected Response Code: 201

    Properties

    Same as Get Role.

    Edit Role

    <?php
    
    $id   = 1;
    $data = array(
        'name' => 'API test role',
        'description' => 'created via AIP',
        'rawPermissions' => array (
            'email:emails' => 
            array (
                'editown',
                'editother',
            ),
        )
    );
    
    // Create new a role of ID 1 is not found?
    $createIfNotFound = true;
    
    $role = $roleApi->edit($id, $data, $createIfNotFound);
    

    Edit a new role. Role that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a role if the given ID does not exist and clears all the role information, adds the information from the request. PATCH fails if the role with the given ID does not exist and updates the role field values with the values form the request.

    HTTP Request

    To edit a role and return a 404 if the role is not found:

    PATCH /roles/ID/edit

    To edit a role and create a new one if the role is not found:

    PUT /roles/ID/edit

    Post Parameters

    Name Description
    name string
    description string
    isAdmin boolean
    rawPermissions array

    Response

    If PUT, the expected response code is 200 if the role was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Role.

    Delete Role

    <?php
    
    $role = $roleApi->delete($id);
    

    Delete a role.

    HTTP Request

    DELETE /roles/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Role.

    Segments

    Use this endpoint to obtain details on Mautic's contact segments or to manipulate contact memberships.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth   = new ApiAuth();
    $auth       = $initAuth->newAuth($settings);
    $apiUrl     = "https://your-mautic.com";
    $api        = new MauticApi();
    $segmentApi = $api->newApi("segments", $auth, $apiUrl);
    

    Get Segment

    <?php
    
    //...
    $segment = $segmentApi->get($id);
    
        "list": {
            "id": 47,
            "isPublished": 1,
            "dateAdded": "2015-07-21T12:27:12-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-21T14:12:03-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "name": "Segment A",
            "alias": "segment-a",
            "description": "This is my first segment created via API.",
            "filters": [
              {
                "glue": "and",
                "field": "city",
                "type": "text",
                "filter": "Prague",
                "display": null,
                "operator": "=",
              }
            ],
            "isGlobal": true
        }
    

    Get an individual segment by ID.

    HTTP Request

    GET /segments/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Segment Properties

    Name Type Description
    id int ID of the segment
    isPublished boolean Whether the segment is published
    dateAdded datetime Date/time segment was created
    createdBy int ID of the user that created the segment
    createdByUser string Name of the user that created the segment
    dateModified datetime/null Date/time segment was last modified
    modifiedBy int ID of the user that last modified the segment
    modifiedByUser string Name of the user that last modified the segment
    name string Segment name
    alias string Segment alias
    description string Segment description
    filters array Smart filters for the segment. See filter properties bellow
    isGlobal boolean Whether the segment is global. 0 means only the author will see it.

    Segment Filter Properties

    Name Type Description
    glue string How to glue the filters to others. Possible values: and, or
    field string Alias of the contact or company field to based the filter on
    object string Object which have the field. Possible values: 'lead' (for contacts), company
    type string Type of the field. Possible values: 'boolean', date (format Y-m-d), datetime (format Y-m-d H:i:s), email, country, locale, lookup, number, tel, region, select, multiselect, text, textarea, time, timezone, url
    operator string Operator used for matching the values. Possible values: '=', !=, empty, !empty, like, !like, regexp, !regexp, startsWith, endsWith, contains

    List Contact Segments

    <?php
    
    //...
    $segments = $segmentApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
      "total": 13,
      "lists": [
        {
            "id": 47,
            "isPublished": 1,
            "dateAdded": "2015-07-21T12:27:12-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-21T14:12:03-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "name": "Segment A",
            "alias": "segment-a",
            "description": "This is my first segment created via API.",
            "filters": [
              {
                "glue": "and",
                "field": "city",
                "type": "text",
                "filter": "Prague",
                "display": null,
                "operator": "=",
              }
            ],
            "isGlobal": true
        },
        ...
      ]
    }
    

    Returns a list of contact segments available to the user. This list is not filterable.

    HTTP Request

    GET /segments

    Response

    Expected Response Code: 200

    See JSON code example.

    Segment Properties

    Name Type Description
    total int Count of all segments
    id int ID of the segment
    isPublished boolean Whether the segment is published
    dateAdded datetime Date/time segment was created
    createdBy int ID of the user that created the segment
    createdByUser string Name of the user that created the segment
    dateModified datetime/null Date/time segment was last modified
    modifiedBy int ID of the user that last modified the segment
    modifiedByUser string Name of the user that last modified the segment
    name string Segment name
    alias string Segment alias
    description string Segment description
    filters array Smart filters for the segment. See filter properties bellow
    isGlobal boolean Whether the segment is global. 0 means only the author will see it.

    Segment Filter Properties

    Name Type Description
    glue string How to glue the filters to others. Possible values: and, or
    field string Alias of the contact or company field to based the filter on
    object string Object which have the field. Possible values: 'lead' (for contacts), company
    type string Type of the field. Possible values: 'boolean', date (format Y-m-d), datetime (format Y-m-d H:i:s), email, country, locale, lookup, number, tel, region, select, multiselect, text, textarea, time, timezone, url
    operator string Operator used for matching the values. Possible values: '=', !=, empty, !empty, like, !like, regexp, !regexp, startsWith, endsWith, contains

    Create Segment

    <?php
    
    $data = array(
        'name'        => 'Segment A',
        'alias'       => 'segment-a',
        'description' => 'This is my first segment created via API.',
        'isPublished' => 1,
        'filters' => array(
            array(
                'glue' => 'and',
                'field' => 'email',
                'object' => 'lead',
                'type' => 'email',
                'filter' => '*@gmail.com',
                'operator' => 'like',
            ),
        ),
    );
    
    $segment = $segmentApi->create($data);
    

    Create a new segment.

    HTTP Request

    POST /segments/new

    Post Parameters

    Name Description
    name Segment name is the only required field
    alias Name alias generated automatically if not set
    description A description of the segment.
    isPublished A value of 0 or 1
    isGlobal boolean
    filters array

    Segment Filter Properties

    Name Type Description
    glue string How to glue the filters to others. Possible values: and, or
    field string Alias of the contact or company field to based the filter on
    object string Object which have the field. Possible values: 'lead' (for contacts), company
    type string Type of the field. Possible values: 'boolean', date (format Y-m-d), datetime (format Y-m-d H:i:s), email, country, locale, lookup, number, tel, region, select, multiselect, text, textarea, time, timezone, url
    operator string Operator used for matching the values. Possible values: '=', !=, empty, !empty, like, !like, regexp, !regexp, startsWith, endsWith, contains

    Response

    Expected Response Code: 201

    Properties

    Same as Get Segment.

    Edit Segment

    <?php
    
    $id   = 1;
    $data = array(
        'name'        => 'New segment name',
        'isPublished' => 0
    );
    
    // Create new a segment of ID 1 is not found?
    $createIfNotFound = true;
    
    $segment = $segmentApi->edit($id, $data, $createIfNotFound);
    

    Edit a new segment. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a segment if the given ID does not exist and clears all the segment information, adds the information from the request. PATCH fails if the segment with the given ID does not exist and updates the segment field values with the values form the request.

    HTTP Request

    To edit a segment and return a 404 if the segment is not found:

    PATCH /segments/ID/edit

    To edit a segment and create a new one if the segment is not found:

    PUT /segments/ID/edit

    Post Parameters

    Name Description
    name Segment name is the only required field
    alias Name alias generated automatically if not set
    description A description of the segment.
    isPublished A value of 0 or 1
    isGlobal boolean
    filters array

    Segment Filter Properties

    Name Type Description
    glue string How to glue the filters to others. Possible values: and, or
    field string Alias of the contact or company field to based the filter on
    object string Object which have the field. Possible values: 'lead' (for contacts), company
    type string Type of the field. Possible values: 'boolean', date (format Y-m-d), datetime (format Y-m-d H:i:s), email, country, locale, lookup, number, tel, region, select, multiselect, text, textarea, time, timezone, url
    operator string Operator used for matching the values. Possible values: '=', !=, empty, !empty, like, !like, regexp, !regexp, startsWith, endsWith, contains

    Response

    If PUT, the expected response code is 200 if the segment was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Segment.

    Delete Segment

    <?php
    
    $segment = $segmentApi->delete($id);
    

    Delete a segment.

    HTTP Request

    DELETE /segments/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Segment.

    Add Contact to a Segment

    <?php
    
    //...
    $response = $segmentApi->addContact($segmentId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually add a contact to a specific segment.

    HTTP Request

    POST /segments/SEGMENT_ID/contact/CONTACT_ID/add

    Response

    Expected Response Code: 200

    See JSON code example.

    Add Contacts to a Segment

    <?php
    
    //...
    $contactIds = ['ids'=>[ 1, 45, 39]];
    $response = $segmentApi->addContact($segmentId, $contactIds);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
         "success":true,
         "details":{
            "1" :{"success":true},
            "45":{"success":true},
            "39":{"success":false}
         }
    }
    

    Manually add contacts to a specific segment.

    HTTP Request

    POST /segments/SEGMENT_ID/contacts/add

    Response

    Expected Response Code: 200

    See JSON code example.

    Remove Contact from a Segment

    <?php
    
    //...
    $response = $segmentApi->removeContact($segmentId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually remove a contact to a specific segment.

    HTTP Request

    POST /segments/SEGMENT_ID/contact/CONTACT_ID/remove

    Response

    Expected Response Code: 200

    See JSON code example.

    Text messages

    Use this endpoint to obtain details on Mautic's Text Messages (SMSes).

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $smsApi   = $api->newApi("smses", $auth, $apiUrl);
    

    Get Text message

    <?php
    
    //...
    $sms = $smsApi->get($id);
    
    {  
        "sms":{  
            "isPublished":true,
            "dateAdded":"2016-09-14T12:14:45+00:00",
            "createdBy":1,
            "createdByUser":"John Doe",
            "dateModified":null,
            "modifiedBy":null,
            "modifiedByUser":null,
            "id":1,
            "name":"Message A",
            "message":"Hello",
            "language":"en",
            "category":null,
            "publishUp":null,
            "publishDown":null,
            "sentCount":0
        }
    }
    

    Get an individual sms by ID.

    HTTP Request

    GET /smses/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Text message Properties

    Name Type Description
    id int ID of the sms
    name string Title of the sms
    message string Message of the sms
    isPublished bool Published state
    publishUp datetime/null Date/time when the sms should be published
    publishDown datetime/null Date/time the sms should be un published
    dateAdded datetime Date/time sms was created
    createdBy int ID of the user that created the sms
    createdByUser string Name of the user that created the sms
    dateModified datetime/null Date/time sms was last modified
    modifiedBy int ID of the user that last modified the sms
    modifiedByUser string Name of the user that last modified the sms
    language string Language locale of the sms
    sentCount int How many times the SMS was sent

    List Text messages

    <?php
    // ...
    
    $smses = $smsApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
        "total":1,
        "smses":[  
            {  
                "isPublished":true,
                "dateAdded":"2016-09-14T12:14:45+00:00",
                "createdBy":1,
                "createdByUser":"John Doe",
                "dateModified":null,
                "modifiedBy":null,
                "modifiedByUser":null,
                "id":1,
                "name":"Message A",
                "message":"Hello",
                "language":"en",
                "category":null,
                "publishUp":null,
                "publishDown":null,
                "sentCount":0
            }
        ]
    }
    

    HTTP Request

    GET /smses

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Text message.

    Create Text message

    <?php 
    
    $data = array(
        'name'        => 'Text message A',
        'message' => 'This is my first sms created via API.',
        'isPublished' => 1
    );
    
    $sms = $smsApi->create($data);
    

    Create a new sms.

    HTTP Request

    POST /smses/new

    Post Parameters

    Name Type Description
    id int ID of the sms
    name string Title of the sms
    message string Message of the sms
    isPublished bool Published state
    publishUp datetime/null Date/time when the sms should be published
    publishDown datetime/null Date/time the sms should be un published
    dateAdded datetime Date/time sms was created
    createdBy int ID of the user that created the sms
    createdByUser string Name of the user that created the sms
    dateModified datetime/null Date/time sms was last modified
    modifiedBy int ID of the user that last modified the sms
    modifiedByUser string Name of the user that last modified the sms
    language string Language locale of the sms
    sentCount int How many times the SMS was sent

    Response

    Expected Response Code: 201

    Properties

    Same as Get Text message.

    Edit Text message

    <?php
    
    $id   = 1;
    $data = array(
        'name'        => 'New sms name',
        'isPublished' => 0
    );
    
    // Create new a sms of ID 1 is not found?
    $createIfNotFound = true;
    
    $sms = $smsApi->edit($id, $data, $createIfNotFound);
    

    Edit a new sms. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a sms if the given ID does not exist and clears all the sms information, adds the information from the request. PATCH fails if the sms with the given ID does not exist and updates the sms field values with the values form the request.

    HTTP Request

    To edit a sms and return a 404 if the sms is not found:

    PATCH /smses/ID/edit

    To edit a sms and create a new one if the sms is not found:

    PUT /smses/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the sms
    name string Title of the sms
    message string Message of the sms
    isPublished bool Published state
    publishUp datetime/null Date/time when the sms should be published
    publishDown datetime/null Date/time the sms should be un published
    language string Language locale of the sms

    Response

    If PUT, the expected response code is 200 if the sms was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Text message.

    Delete Text message

    <?php
    
    $sms = $smsApi->delete($id);
    

    Delete a sms.

    HTTP Request

    DELETE /smses/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Text message.

    Send SMS to Contact

    <?php
    
    $sms = $smsApi->sendToContact($smsId, $contactId);
    

    Send a predefined sms to existing contact.

    HTTP Request

    GET /smses/ID/contact/CONTACT_ID/send

    Response

    Expected Response Code: 200

    Properties json { "success": 1, "status": "Delivered" }

    Stages

    Use this endpoint to obtain details on Mautic's contact stages.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $stageApi = $api->newApi("stages", $auth, $apiUrl);
    

    Get Stage

    <?php
    
    //...
    $stage = $stageApi->get($id);
    
        "stage": {
            "id": 47,
            "isPublished": 1,
            "dateAdded": "2015-07-21T12:27:12-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-21T14:12:03-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "name": "Stage A",
            "category": null,
            "description": "This is my first stage created via API.",
            "weight": 0,
            "publishUp": "2015-07-21T14:12:03-05:00",
            "publishDown": "2015-07-21T14:12:03-05:00"
        }
    

    Get an individual stage by ID.

    HTTP Request

    GET /stages/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Stage Properties

    Name Type Description
    id int ID of the stage
    isPublished boolean Whether the stage is published
    dateAdded datetime Date/time stage was created
    createdBy int ID of the user that created the stage
    createdByUser string Name of the user that created the stage
    dateModified datetime/null Date/time stage was last modified
    modifiedBy int ID of the user that last modified the stage
    modifiedByUser string Name of the user that last modified the stage
    name string Stage name
    category int Stage category ID
    description string Stage description
    weight int Stage's weight
    publishUp datetime Date/time stage should be published
    publishDown datetime Date/time stage should be unpublished

    List Contact Stages

    <?php
    
    //...
    $stages = $stageApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
      "total": 4,
      "stages": [
        {
            "id": 47,
            "isPublished": 1,
            "dateAdded": "2015-07-21T12:27:12-05:00",
            "createdBy": 1,
            "createdByUser": "Joe Smith",
            "dateModified": "2015-07-21T14:12:03-05:00",
            "modifiedBy": 1,
            "modifiedByUser": "Joe Smith",
            "name": "Stage A",
            "category": null,
            "description": "This is my first stage created via API.",
            "weight": 0,
            "publishUp": "2015-07-21T14:12:03-05:00",
            "publishDown": "2015-07-21T14:12:03-05:00"
        },
        ...
      ]
    }
    

    HTTP Request

    GET /stages

    Response

    Expected Response Code: 200

    See JSON code example.

    Stage Properties

    Name Type Description
    total int Count of all stages
    id int ID of the stage
    isPublished boolean Whether the stage is published
    dateAdded datetime Date/time stage was created
    createdBy int ID of the user that created the stage
    createdByUser string Name of the user that created the stage
    dateModified datetime/null Date/time stage was last modified
    modifiedBy int ID of the user that last modified the stage
    modifiedByUser string Name of the user that last modified the stage
    name string Stage name
    category int Stage category ID
    description string Stage description
    weight int Stage's weight
    publishUp datetime Date/time stage should be published
    publishDown datetime Date/time stage should be unpublished

    Create Stage

    <?php 
    
    $data = array(
        'name'        => 'Stage A',
        'weight'      => 5,
        'description' => 'This is my first stage created via API.',
        'isPublished' => 1
    );
    
    $stage = $stageApi->create($data);
    

    Create a new stage.

    HTTP Request

    POST /stages/new

    Post Parameters

    Name Description
    name Stage name is the only required field
    weight int
    description A description of the stage.
    isPublished A value of 0 or 1

    Response

    Expected Response Code: 201

    Properties

    Same as Get Stage.

    Edit Stage

    <?php
    
    $id   = 1;
    $data = array(
        'name'        => 'New stage name',
        'isPublished' => 0
    );
    
    // Create new a stage of ID 1 is not found?
    $createIfNotFound = true;
    
    $stage = $stageApi->edit($id, $data, $createIfNotFound);
    

    Edit a new stage. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a stage if the given ID does not exist and clears all the stage information, adds the information from the request. PATCH fails if the stage with the given ID does not exist and updates the stage field values with the values form the request.

    HTTP Request

    To edit a stage and return a 404 if the stage is not found:

    PATCH /stages/ID/edit

    To edit a stage and create a new one if the stage is not found:

    PUT /stages/ID/edit

    Post Parameters

    Name Description
    name Stage name is the only required field
    alias Name alias generated automatically if not set
    description A description of the stage.
    isPublished A value of 0 or 1
    weight int

    Response

    If PUT, the expected response code is 200 if the stage was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Stage.

    Delete Stage

    <?php
    
    $stage = $stageApi->delete($id);
    

    Delete a stage.

    HTTP Request

    DELETE /stages/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Stage.

    Add Contact to a Stage

    <?php
    
    //...
    $response = $stageApi->addContact($stageId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually add a contact to a specific stage.

    HTTP Request

    POST /stages/STAGE_ID/contact/CONTACT_ID/add

    Response

    Expected Response Code: 200

    See JSON code example.

    Remove Contact from a Stage

    <?php
    
    //...
    $response = $stageApi->removeContact($stageId, $contactId);
    if (!isset($response['success'])) {
        // handle error
    }
    
    {
        "success": true
    }
    

    Manually remove a contact from a specific stage.

    HTTP Request

    POST /stages/STAGE_ID/contact/CONTACT_ID/remove

    Response

    Expected Response Code: 200

    See JSON code example.

    Stats

    This endpoint is useful for downloading a full statistical table.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $statsApi = $api->newApi("stats", $auth, $apiUrl);
    

    Get Available Stat Tables

    <?php
    
    //...
    $tables = $statsApi->get();
    
    {
      "availableTables": [
        "asset_downloads",
        "audit_log",
        "campaign_lead_event_log",
        "campaign_leads",
        "channel_url_trackables",
        "companies_leads",
        "dynamic_content_lead_data",
        "dynamic_content_stats",
        "email_stat_replies",
        "email_stats",
        "email_stats_devices",
        "focus_stats",
        "form_submissions",
        "ip_addresses",
        "lead_categories",
        "lead_companies_change_log",
        "lead_devices",
        "lead_donotcontact",
        "lead_event_log",
        "lead_frequencyrules",
        "lead_lists_leads",
        "lead_points_change_log",
        "lead_stages_change_log",
        "lead_utmtags",
        "page_hits",
        "page_redirects",
        "plugin_citrix_events",
        "point_lead_action_log",
        "point_lead_event_log",
        "push_notification_stats",
        "sms_message_stats",
        "stage_lead_action_log",
        "tweet_stats",
        "video_hits",
        "webhook_logs"
      ],
      "tableColumns": {
        "asset_downloads": [
          "asset_id",
          "code",
          "date_download",
          "email_id",
          "id",
          "ip_id",
          "lead_id",
          "referer",
          "source",
          "source_id",
          "tracking_id"
        ],
        "audit_log": [
          "action",
          "bundle",
          "date_added",
          "details",
          "id",
          "ip_address",
          "object",
          "object_id",
          "user_id",
          "user_name"
        ],
        "campaign_lead_event_log": [
          "campaign_id",
          "channel",
          "channel_id",
          "date_triggered",
          "event_id",
          "id",
          "ip_id",
          "is_scheduled",
          "lead_id",
          "metadata",
          "non_action_path_taken",
          "rotation",
          "system_triggered",
          "trigger_date"
        ],
        "campaign_leads": [
          "campaign_id",
          "date_added",
          "date_last_exited",
          "lead_id",
          "manually_added",
          "manually_removed",
          "rotation"
        ],
        "channel_url_trackables": [
          "channel",
          "channel_id",
          "hits",
          "redirect_id",
          "unique_hits"
        ],
        "companies_leads": [
          "company_id",
          "date_added",
          "is_primary",
          "lead_id",
          "manually_added",
          "manually_removed"
        ],
        "dynamic_content_lead_data": [
          "date_added",
          "dynamic_content_id",
          "id",
          "lead_id",
          "slot"
        ],
        "dynamic_content_stats": [
          "date_sent",
          "dynamic_content_id",
          "id",
          "last_sent",
          "lead_id",
          "sent_count",
          "sent_details",
          "source",
          "source_id",
          "tokens"
        ],
        "email_stat_replies": [
          "date_replied",
          "id",
          "message_id",
          "stat_id"
        ],
        "email_stats": [
          "copy_id",
          "date_read",
          "date_sent",
          "email_address",
          "email_id",
          "id",
          "ip_id",
          "is_failed",
          "is_read",
          "last_opened",
          "lead_id",
          "list_id",
          "open_count",
          "open_details",
          "retry_count",
          "source",
          "source_id",
          "tokens",
          "tracking_hash",
          "viewed_in_browser"
        ],
        "email_stats_devices": [
          "date_opened",
          "device_id",
          "id",
          "ip_id",
          "stat_id"
        ],
        "focus_stats": [
          "date_added",
          "focus_id",
          "id",
          "lead_id",
          "type",
          "type_id"
        ],
        "form_submissions": [
          "date_submitted",
          "form_id",
          "id",
          "ip_id",
          "lead_id",
          "page_id",
          "referer",
          "tracking_id"
        ],
        "ip_addresses": [
          "id",
          "ip_address",
          "ip_details"
        ],
        "lead_categories": [
          "category_id",
          "date_added",
          "id",
          "lead_id",
          "manually_added",
          "manually_removed"
        ],
        "lead_companies_change_log": [
          "action_name",
          "company_id",
          "date_added",
          "event_name",
          "id",
          "lead_id",
          "type"
        ],
        "lead_devices": [
          "client_info",
          "date_added",
          "device",
          "device_brand",
          "device_fingerprint",
          "device_model",
          "device_os_name",
          "device_os_platform",
          "device_os_shortname",
          "device_os_version",
          "id",
          "lead_id",
          "tracking_id"
        ],
        "lead_donotcontact": [
          "channel",
          "channel_id",
          "comments",
          "date_added",
          "id",
          "lead_id",
          "reason"
        ],
        "lead_event_log": [
          "action",
          "bundle",
          "date_added",
          "id",
          "lead_id",
          "object",
          "object_id",
          "properties",
          "user_id",
          "user_name"
        ],
        "lead_frequencyrules": [
          "channel",
          "date_added",
          "frequency_number",
          "frequency_time",
          "id",
          "lead_id",
          "pause_from_date",
          "pause_to_date",
          "preferred_channel"
        ],
        "lead_lists_leads": [
          "date_added",
          "leadlist_id",
          "lead_id",
          "manually_added",
          "manually_removed"
        ],
        "lead_points_change_log": [
          "action_name",
          "date_added",
          "delta",
          "event_name",
          "id",
          "ip_id",
          "lead_id",
          "type"
        ],
        "lead_stages_change_log": [
          "action_name",
          "date_added",
          "event_name",
          "id",
          "lead_id",
          "stage_id"
        ],
        "lead_utmtags": [
          "date_added",
          "id",
          "lead_id",
          "query",
          "referer",
          "remote_host",
          "url",
          "user_agent",
          "utm_campaign",
          "utm_content",
          "utm_medium",
          "utm_source",
          "utm_term"
        ],
        "page_hits": [
          "browser_languages",
          "city",
          "code",
          "country",
          "date_hit",
          "date_left",
          "device_id",
          "email_id",
          "id",
          "ip_id",
          "isp",
          "lead_id",
          "organization",
          "page_id",
          "page_language",
          "query",
          "redirect_id",
          "referer",
          "region",
          "remote_host",
          "source",
          "source_id",
          "tracking_id",
          "url",
          "url_title",
          "user_agent"
        ],
        "page_redirects": [
          "checked_out",
          "checked_out_by",
          "checked_out_by_user",
          "created_by",
          "created_by_user",
          "date_added",
          "date_modified",
          "hits",
          "id",
          "is_published",
          "modified_by",
          "modified_by_user",
          "redirect_id",
          "unique_hits",
          "url"
        ],
        "plugin_citrix_events": [
          "email",
          "event_date",
          "event_desc",
          "event_name",
          "event_type",
          "id",
          "lead_id",
          "product"
        ],
        "point_lead_action_log": [
          "date_fired",
          "ip_id",
          "lead_id",
          "point_id"
        ],
        "point_lead_event_log": [
          "date_fired",
          "event_id",
          "ip_id",
          "lead_id"
        ],
        "push_notification_stats": [
          "click_count",
          "click_details",
          "date_clicked",
          "date_read",
          "date_sent",
          "id",
          "ip_id",
          "is_clicked",
          "last_clicked",
          "lead_id",
          "list_id",
          "notification_id",
          "retry_count",
          "source",
          "source_id",
          "tokens",
          "tracking_hash"
        ],
        "sms_message_stats": [
          "date_sent",
          "id",
          "ip_id",
          "lead_id",
          "list_id",
          "sms_id",
          "source",
          "source_id",
          "tokens",
          "tracking_hash"
        ],
        "stage_lead_action_log": [
          "date_fired",
          "ip_id",
          "lead_id",
          "stage_id"
        ],
        "tweet_stats": [
          "date_sent",
          "favorite_count",
          "handle",
          "id",
          "is_failed",
          "lead_id",
          "response_details",
          "retry_count",
          "retweet_count",
          "source",
          "source_id",
          "tweet_id",
          "twitter_tweet_id"
        ],
        "video_hits": [
          "browser_languages",
          "channel",
          "channel_id",
          "city",
          "code",
          "country",
          "date_hit",
          "date_left",
          "duration",
          "guid",
          "id",
          "ip_id",
          "isp",
          "lead_id",
          "organization",
          "page_language",
          "query",
          "referer",
          "region",
          "remote_host",
          "time_watched",
          "url",
          "user_agent"
        ],
        "webhook_logs": [
          "date_added",
          "id",
          "note",
          "runtime",
          "status_code",
          "webhook_id"
        ]
      }
    }
    

    HTTP Request

    GET /stats

    Response

    Expected Response Code: 200

    See JSON code example.

    Stats Properties

    Name Type Description
    availableTables array List of available tables which can be used in this endpoint
    stats array An empty array of stats, because no table was defined

    Get Stats from a table

    <?php
    // Example setup variables:
    $table = 'asset_downloads';
    $start = 0;
    $limit = 50;
    $order = array(
        array(
          'col' => 'id',
          'dir' => 'asc'
        )
    );
    $where = array(
        array(
          'col' => 'id',
          'expr' => 'gt',
          'val' => 3,
        )
    );
    
    $stats = $statsApi->get($table, $start, $limit, $order, $where);
    
    {
      "stats":[
        {
          "id":"1",
          "asset_id":"1",
          "ip_id":"1",
          "lead_id":"31",
          "date_download":"2016-06-30 08:51:22",
          "code":"200",
          "tracking_id":"b3259e7709f35b7428b7bffcbb3d1d713ac1526c"
        },
        [...]
      ]
    }
    

    HTTP Request

    GET /stats/TABLE

    Request Properties

    Name Type Description
    start int Which row to start on
    limit int How many rows to return
    order array An array of arrays which contain ordering (example above)
    where array An array of arrays which contain where conditions (example above). As the expr param can be used most of the methods from DBAL Doctrine where methods.

    If using cURL, a query parameter may look something like where%5B0%5D%5Bcol%5D=id&where%5B0%5D%5Bexpr%5D=eq&where%5B0%5D%5Bval%5D=3 which is the equivalent to the following:

    array(
        array(
            'col'  => 'id',
            'expr' => 'eq',
            'val'  => 3,
        )
    );
    

    Response

    Expected Response Code: 200

    See JSON code example.

    Stats Properties

    Different for every table. It simply returns rows or requested table.

    Tags

    Use this endpoint to obtain details on Mautic's tags. Implemented in Mautic 2.12.0.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth        = new ApiAuth();
    $auth            = $initAuth->newAuth($settings);
    $apiUrl          = "https://your-mautic.com";
    $api             = new MauticApi();
    $tagApi = $api->newApi("tags", $auth, $apiUrl);
    

    Get Tag

    <?php
    
    //...
    $tag = $tagApi->get($id);
    
    {  
        "tag": {
            "id": 34,
            "tag": "tagA",
        }
    }
    

    Get an individual tag by ID.

    HTTP Request

    GET /tags/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Tag Properties

    Name Type Description
    id int ID of the tag
    tag string Title of the tag

    List Tags

    <?php
    // ...
    
    $tags = $tagApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
        "total":1,
        "tags":[  
            {
                "id": 34,
                "tag": "tagA",
            }
        ]
    }
    

    HTTP Request

    GET /tags

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Tag.

    Create Tag

    <?php
    
    $data = array(
        'tag' => 'Tag A',
    );
    
    $tag = $tagApi->create($data);
    

    Create a new tag.

    HTTP Request

    POST /tags/new

    Post Parameters

    Name Type Description
    id int ID of the tag
    tag string Title of the tag

    Response

    Expected Response Code: 201

    Properties

    Same as Get Tag.

    Edit Tag

    <?php
    
    $id   = 1;
    $data = array(
        'tag' => 'Tag B',
    );
    
    // Create new a tag of ID 1 is not found?
    $createIfNotFound = true;
    
    $tag = $tagApi->edit($id, $data, $createIfNotFound);
    

    Edit a new tag. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a tag if the given ID does not exist and clears all the tag information, adds the information from the request. PATCH fails if the tag with the given ID does not exist and updates the tag field values with the values form the request.

    HTTP Request

    To edit a tag and return a 404 if the tag is not found:

    PATCH /tags/ID/edit

    To edit a tag and create a new one if the tag is not found:

    PUT /tags/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the tag
    tag string Title of the tag

    Response

    If PUT, the expected response code is 200 if the tag was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Tag.

    Delete Tag

    <?php
    
    $tag = $tagApi->delete($id);
    

    Delete a tag.

    HTTP Request

    DELETE /tags/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get Tag.

    Users

    Use this endpoint to obtain details on Mautic's users (administrators).

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    $apiUrl   = "https://your-mautic.com";
    $api      = new MauticApi();
    $userApi  = $api->newApi("users", $auth, $apiUrl);
    

    Get User

    <?php
    
    //...
    $user = $userApi->get($id);
    
    {  
      "user":{  
        "isPublished":true,
        "dateAdded":"2016-11-09T14:23:44+00:00",
        "createdBy":1,
        "createdByUser":"John Doe",
        "dateModified":null,
        "modifiedBy":null,
        "modifiedByUser":null,
        "id":6,
        "username":"apitest",
        "firstName":"John",
        "lastName":"Doe",
        "email":"john@doe.com",
        "position":null,
        "role":{  
          "createdByUser":null,
          "modifiedByUser":null,
          "id":1,
          "name":"Administrator",
          "description":"Full system access",
          "isAdmin":true,
          "rawPermissions":null
        },
        "timezone":null,
        "locale":null,
        "lastLogin":null,
        "lastActive":null,
        "onlineStatus":"offline",
        "signature":null
      }
    }
    

    Get an individual user by ID.

    HTTP Request

    GET /users/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    User Properties

    Name Type Description
    id int ID of the contact
    dateAdded datetime Date/time contact was created
    createdBy int ID of the user that created the contact
    createdByUser string Name of the user that created the contact
    dateModified datetime/null Date/time contact was last modified
    lastActive datetime/null Date/time when the user last active
    modifiedBy int ID of the user that last modified the contact
    modifiedByUser string Name of the user that last modified the contact
    username string Username which can be used for log in to Mautic.
    firstName string First Name of the user
    lastName string Last Name of the user
    email string Email of the user
    position string User's position title
    role array List of roles of the user
    timezone string Timezone of the user
    onlineStatus string Online status of the user
    signature string Signature of the user which can be used in the emails

    List Contact Users

    <?php
    
    //...
    $users = $userApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {  
      "total":2,
      "users":[  
        {  
          "isPublished":true,
          "dateAdded":"2016-08-01T11:52:15+00:00",
          "createdBy":null,
          "createdByUser":" ",
          "dateModified":"2016-09-26T15:02:32+00:00",
          "modifiedBy":null,
          "modifiedByUser":" ",
          "id":2,
          "username":"test",
          "firstName":"John",
          "lastName":"Doe",
          "email":"john@doe.com",
          "position":null,
          "role":{  
            "createdByUser":"John Doe",
            "modifiedByUser":null,
            "id":4,
            "name":"edit own contacts",
            "description":null,
            "isAdmin":false,
            "rawPermissions":{  
              "lead:leads":[  
                "viewown",
                "editown",
                "create",
                "deleteown"
              ],
              "lead:lists":[  
                "viewother"
              ]
            }
          },
          "timezone":null,
          "locale":null,
          "lastLogin":"2016-09-26T15:03:25+00:00",
          "lastActive":"2016-09-26T15:19:15+00:00",
          "onlineStatus":"offline",
          "signature":"Best regards,&#10;Yours&#10;|FROM_NAME|"
        },
        [...]
      ]
    }
    

    HTTP Request

    GET /users

    Response

    Expected Response Code: 200

    See JSON code example.

    User Properties

    Name Type Description
    id int ID of the contact
    dateAdded datetime Date/time contact was created
    createdBy int ID of the user that created the contact
    createdByUser string Name of the user that created the contact
    dateModified datetime/null Date/time contact was last modified
    lastActive datetime/null Date/time when the user last active
    modifiedBy int ID of the user that last modified the contact
    modifiedByUser string Name of the user that last modified the contact
    username string Username which can be used for log in to Mautic.
    firstName string First Name of the user
    lastName string Last Name of the user
    email string Email of the user
    position string User's position title
    role array List of roles of the user
    timezone string Timezone of the user
    onlineStatus string Online status of the user
    signature string Signature of the user which can be used in the emails

    Create User

    <?php 
    
    $data = array(
        'username' => 'apitest',
        'firstName' => 'John',
        'lastName' => 'Doe',
        'email' => 'john@doe.com',
        'plainPassword' => array(
            'password' => 'topSecret007',
            'confirm' => 'topSecret007',
        ),
        'role' => 1,
    );
    
    $user = $userApi->create($data);
    

    Create a new user.

    HTTP Request

    POST /users/new

    Post Parameters

    Name Description
    username string
    firstName string
    lastName string
    email string
    position string
    role array
    timezone string
    onlineStatus string
    signature string
    plainPassword array

    Response

    Expected Response Code: 201

    Properties

    Same as Get User.

    Edit User

    <?php
    
    $id   = 1;
    $data = array(
        'lastName' => 'Doeboe',
    );
    
    // Create new a user of ID 1 is not found?
    $createIfNotFound = true;
    
    $user = $userApi->edit($id, $data, $createIfNotFound);
    

    Edit a new user. User that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a user if the given ID does not exist and clears all the user information, adds the information from the request. PATCH fails if the user with the given ID does not exist and updates the user field values with the values form the request.

    HTTP Request

    To edit a user and return a 404 if the user is not found:

    PATCH /users/ID/edit

    To edit a user and create a new one if the user is not found:

    PUT /users/ID/edit

    Post Parameters

    Name Description
    username string
    firstName string
    lastName string
    email string
    position string
    role array
    timezone string
    signature string

    Response

    If PUT, the expected response code is 200 if the user was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get User.

    Delete User

    <?php
    
    $user = $userApi->delete($id);
    

    Delete a user.

    HTTP Request

    DELETE /users/ID/delete

    Response

    Expected Response Code: 200

    Properties

    Same as Get User.

    Get Self User

    <?php
    
    $user = $userApi->getSelf();
    

    Get a self user.

    HTTP Request

    GET /users/self

    Response

    Expected Response Code: 200

    Properties

    Same as Get User.

    Check User Permissions

    <?php
    $permission = array('user:users:create', 'user:users:edit');
    $user = $userApi->checkPermission($id, $permission);
    

    Get a self user.

    HTTP Request

    GET /users/ID/permissioncheck

    Response

    Expected Response Code: 200 json { "user:users:create":true, "user:users:edit":true }

    Properties

    array of requested permissions of string in case of just one

    Webhooks

    Use this endpoint to obtain details on Mautic's webhooks. Implemented in Mautic 2.8.0.

    <?php
    use Mautic\MauticApi;
    use Mautic\Auth\ApiAuth;
    
    // ...
    $initAuth        = new ApiAuth();
    $auth            = $initAuth->newAuth($settings);
    $apiUrl          = "https://your-mautic.com";
    $api             = new MauticApi();
    $webhookApi      = $api->newApi("webhooks", $auth, $apiUrl);
    

    Get Webhook

    <?php
    
    //...
    $webhook = $webhookApi->get($id);
    
    {
      "hook": {
        "isPublished": false,
        "dateAdded": "2017-06-07T08:54:46+00:00",
        "dateModified": "2017-06-09T07:16:23+00:00",
        "createdBy": 1,
        "createdByUser": "John Doe",
        "modifiedBy": null,
        "modifiedByUser": " ",
        "id": 31,
        "name": "test",
        "description": "Created via API",
        "webhookUrl": "https:\/\/johndoe.com",
        "secret": "webhookSecretKey",
        "eventsOrderbyDir": "DESC",
        "category": {
          "createdByUser": "John Doe",
          "modifiedByUser": "John Doe",
          "id": 1,
          "title": "Important",
          "alias": "important",
          "description": null,
          "color": null,
          "bundle": "Webhook"
        },
        "triggers": [
          "mautic.lead_post_delete",
          "mautic.lead_points_change",
          "mautic.lead_post_save_new",
          "mautic.lead_post_save_update"
        ]
      }
    }
    

    Get an individual webhook by ID.

    HTTP Request

    GET /hooks/ID

    Response

    Expected Response Code: 200

    See JSON code example.

    Webhook Properties

    Name Type Description
    id int ID of the webhook
    name string Title of the webhook
    description string Description of the webhook
    webhookUrl string Url to send the webhook payload to
    secret string Secret key used for authenticity verification
    eventsOrderbyDir Order direction for queued events in one webhook. Can be "DESC" or "ASC"
    isPublished bool Published state
    publishUp datetime/null Date/time when the webhook should be published
    publishDown datetime/null Date/time the webhook should be un published
    dateAdded datetime Date/time webhook was created
    createdBy int ID of the user that created the webhook
    createdByUser string Name of the user that created the webhook
    dateModified datetime/null Date/time webhook was last modified
    modifiedBy int ID of the user that last modified the webhook
    modifiedByUser string Name of the user that last modified the webhook
    category null/object Category
    triggers array List of triggers available in Mautic

    List Webhooks

    <?php
    // ...
    
    $webhooks = $webhookApi->getList($searchFilter, $start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal);
    
    {
      "total": 1,
      "hooks": {
        "31": {
          "isPublished": false,
          "dateAdded": "2017-06-07T08:54:46+00:00",
          "dateModified": "2017-06-09T07:16:23+00:00",
          "createdBy": 1,
          "createdByUser": "John Doe",
          "modifiedBy": null,
          "modifiedByUser": " ",
          "id": 31,
          "name": "Deleted contact",
          "description": "Notify me when a contact is deleted",
          "webhookUrl": "https:\/\/johndoe.com",
          "secret": "webhookSecretKey",
          "eventsOrderbyDir": "DESC",
          "category": null,
          "triggers": [
            "mautic.lead_post_delete",
          ]
        }
      }
    }
    

    HTTP Request

    GET /hooks

    Query Parameters

    Name Description
    search String or search command to filter entities by.
    start Starting row for the entities returned. Defaults to 0.
    limit Limit number of entities to return. Defaults to the system configuration for pagination (30).
    orderBy Column to sort by. Can use any column listed in the response.
    orderByDir Sort direction: asc or desc.
    publishedOnly Only return currently published entities.
    minimal Return only array of entities without additional lists in it.

    Response

    Expected Response Code: 200

    See JSON code example.

    Properties

    Same as Get Webhook.

    Create Webhook

    <?php
    
    $data = array(
        'name' => 'test',
        'description' => 'Created via API',
        'webhookUrl' => 'http://some.url',
        'secret': 'webhookSecretKey',
        'eventsOrderbyDir' => "ASC",
        'triggers' => array(
            'mautic.lead_post_save_update',
            'mautic.lead_post_save_new',
        )
    );
    
    $webhook = $webhookApi->create($data);
    

    Create a new webhook.

    HTTP Request

    POST /hooks/new

    Post Parameters

    Name Type Description
    id int ID of the webhook
    name string Title of the webhook
    description string Description of the webhook
    webhookUrl string URL to send the webhook payload to
    secret string (Optional) Secret key used for authenticity verification
    eventsOrderbyDir Order direction for queued events in one webhook. Can be "DESC" or "ASC"
    isPublished bool Published state

    Response

    Expected Response Code: 201

    Properties

    Same as Get Webhook.

    Edit Webhook

    <?php
    
    $id   = 1;
    $data = array(
        'name' => 'Rename webhook 1 to this',
    );
    
    // Create new a webhook of ID 1 is not found?
    $createIfNotFound = true;
    
    $webhook = $webhookApi->edit($id, $data, $createIfNotFound);
    

    Edit a new webhook. Note that this supports PUT or PATCH depending on the desired behavior.

    PUT creates a webhook if the given ID does not exist and clears all the webhook information, adds the information from the request. PATCH fails if the webhook with the given ID does not exist and updates the webhook field values with the values form the request.

    HTTP Request

    To edit a webhook and return a 404 if the webhook is not found:

    PATCH /hooks/ID/edit

    To edit a webhook and create a new one if the webhook is not found:

    PUT /hooks/ID/edit

    Post Parameters

    Name Type Description
    id int ID of the webhook
    name string Title of the webhook
    description string Description of the webhook
    webhookUrl string Url to send the webhook payload to
    secret string Secret key used for authenticity verification
    eventsOrderbyDir Order direction for queued events in one webhook. Can be "DESC" or "ASC"
    isPublished bool Published state

    Response

    If PUT, the expected response code is 200 if the webhook was edited or 201 if created.

    If PATCH, the expected response code is 200.

    Properties

    Same as Get Webhook.

    Delete Webhook

    <?php
    
    $webhook = $webhookApi->delete($id);
    

    Delete a webhook.

    HTTP Request

    DELETE /hooks/ID/delete

    Response

    Expected Response Code: 200

    Same as Get Webhook.

    List available webhook triggers

    <?php
    
    $webhook = $webhookApi->getTriggers();
    

    List webhook triggers

    HTTP Request

    GET /hooks/triggers

    Response

    Expected Response Code: 200

    {
      "triggers": {
        "mautic.lead_post_delete": {
          "label": "Contact Delete Event",
          "description": "mautic.lead.webhook.event.lead.deleted_desc"
        },
        "mautic.lead_points_change": {
          "label": "Contact Point Change (Increase \/ Decrease) Event",
          "description": "mautic.lead.webhook.event.lead.points_desc"
        },
        "mautic.lead_post_save_update": {
          "label": "Contact Updated Event",
          "description": "mautic.lead.webhook.event.lead.update_desc"
        },
        "mautic.email_on_open": {
          "label": "Email Open Event",
          "description": "mautic.email.webhook.event.open_desc"
        },
        "mautic.form_on_submit": {
          "label": "Form Submit Event",
          "description": "mautic.form.webhook.event.form.submit_desc"
        },
        "mautic.lead_post_save_new": {
          "label": "New Contact Event",
          "description": "mautic.lead.webhook.event.lead.new_desc"
        },
        "mautic.page_on_hit": {
          "label": "Page Hit Event",
          "description": "mautic.page.webhook.event.hit_desc"
        }
      }
    }
    

    Webhooks

    Webhook is a universal way how to send data about leads, pages, forms and events. The data is sent in real-time when an action occurs so the system which listens form Mautic webhook data can process them without the need for a periodic scanning if Mautic has some new data.

    Available webhook actions

    Mautic can send webhook payload on these actions:

    The webhook workflow

    The example workflow below describes a real-life workflow to get an idea how the webhooks can be used. Let's imagine we have a project management system (PMS) and we want to create a new issue when a lead submits a form.

    1. A lead submits a Mautic form.
    2. Mautic saves the form.
    3. Mautic checks if there is a webhook with the Form submit event. If there is, Mautic sends the data to the URL address defined in the webhook.
    4. PMS receives the data about the form submission and creates a new issue from it.

    Create a webhook

    It is possible to create multiple different webhooks. That will allow you to send different information to different apps/scripts.

    1. Open the right hand side menu (click the cog icon in the top right corner) and select Webhooks.
    2. Create a new webhook.
    3. Fill in a Name, Webhook POST Url (see the next paragraph if you don't have one) and select which Webhook Events should trigger this webhook.

    Test a webhook

    The easiest way how to test a webhook payload is to use a service like RequestBin. RequestBin lets you create a URL which you can set as the Webhook POST Url in Mautic. Then click the Apply button to save it and then click the Send Test Payload button. That will send a test payload data to RequestBin and you will be able to see it at your RequestBin.

    When you have created your testing webhook, you can test the real data it sends when a defined action is triggered.

    Immediate or queued webhooks

    There is an option to queue webhooks for background execution. The reason behind it is that every time an action like contact update happens which has the webhook listener attached to it, the action has to wait for the webhook response until the webhook response returns or when it times out after 10 seconds. So it is up to the webhook receiver how fast the contact update is.

    This lag can be more visible when you do a CSV import. It may be slow when it is waiting a second or two for webhook response for every imported contact.

    If you want to avoid this lag, configure the webhook queue in the configuration and add this command to your cron tab: app/console mautic:webhooks:process. This way every time the webhook is triggered, the action is queued as a new row into database, so it is much faster and then the command will make the requests which may take some time. The caveat to this optimization is that the webhooks are not fired every time the action happens, but every time the command runs.

    Queued event order

    Mautic will send several events in one webhook if they happen before the queue trigger command runs. Mautic's default order of those events is chronological. But Zapier integration which use webhooks heavily requires reverse chronological order. Therefore the new option to configure the order was added to webhooks as well as to the global configuration. Webhook configuration overwrites the global configuration, but if not set, the global configuration order value is applied.

    Authenticity verification

    During webhook creation you can provide a secret key, if no secret key is provided it will be automatically generated. This secret has to be shared with third-party application which will receive webhooks from mautic. Indeed, in order to verify authenticity of the data provided in a webhook, Mautic add an header Webhook-Signature on every webhook call. A third-party application can compute a base64 encoded HMAC-SHA256 signature with the webhook secret on the (raw) payload body to verify this signature and prove authenticity of the webhook data.

    Examples webhook script

    If you need an idea about how to receive Mautic webhook data in your app, this script can be used as a starting point. The script will log the request and return the payload. Place this script on a publicly accessible URL (i.e. `http://yourwebsite.com/webhookTest.php), then fill in the Mautic Webhook POST Url to this script.

    <?php
    // webhookTest.php
    
    /**
     * A helper class to log and get the Mautic webhook request
     */
    class webhookTest {
        /**
         * Log a message to a file
         *
         * @param  mixed $message
         * @param  string $type [info|error|request]
         */
        public function log($message, $type = 'info')
        {
            $prefix = 'webhookLog_';
            $file = $type . '.log';
            $date = new DateTime();
            error_log($date->format('Y-m-d H:i:s') . ' ' . $message . "\n\n", 3, $prefix . $file);
        }
        /**
         * Get the request JSON object and log the request
         *
         * @return object
         */
        public function getRequest()
        {
            $rawData = file_get_contents("php://input");
            $this->log($rawData, 'request');
            return $rawData;
        }
    }
    
    $secret = 'mySecret';
    $webhook = new webhookTest;
    $rawData = $webhook->getRequest();
    
    // optional signature verification
    $headers = getallheaders();
    $receivedSignature = $headers['Webhook-Signature'];
    $computedSignature = base64_encode(hash_hmac('sha256', $rawData, $secret, true));
    
    if ($receivedSignature === $computedSignature) {
        $webhook->log('Webhook authenticity verification OK', 'request');
    } else {
        $webhook->log('Webhook not authentic!', 'request');
    }
    
    // @todo Process the $requestData as needed
    $requestData = json_decode($rawData);
    

    Additionally here are another example in NodeJS (with express): ```javascript 'use strict';

    const express = require('express'); const crypto = require('crypto'); const app = express(); const port = 3000; const SECRET = 'mySecret';

    // save raw body app.use ((req, res, next) => { let data = ''; req.setEncoding('utf8');

    req.on('data', chunk => data += chunk); req.on('end', () => { req.body = data; return next(); }); });

    app.post('/webhook', (req, res) => {

    // optional signature verification const receivedSignature = req.headers['webhook-signature']; console.log('Received signature (in header):', receivedSignature);

    const computedSignature = crypto.createHmac('sha256', SECRET).update(req.body).digest('base64'); console.log('Computed signature (from body):', computedSignature);

    if (receivedSignature === computedSignature) { console.log('Webhook authenticity verification OK'); } else { console.log('Webhook not authentic!'); }

    // TODO: process body const body = JSON.parse(req.body);

    res.send(); });

    app.listen(port, () => console.log(App listening on port ${port}!)); ``` If you'd like to extend the webhook functionality with your plugin, read more in the plugin docs.

    Javascript SDK

    Basic Tracking and Page Views

    <script>
        (function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
            w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
            m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://youraccount.maatoo.io/mtc.js','mt');
    
        mt('send', 'pageview');
    </script>
    

    Pageviews

    Page Views with callbacks

    mt('send', 'pageview', {}, {
        onload: function() {
            redirect();
        },
        onerror: function() {
            redirect();
        }
    });
    

    Custom Parameters

    Add parameters to page view events.

    mt('send', 'pageview', {email: 'my@email.com', firstname: 'John'});
    
    mt('send', 'pageview', {email: 'my@email.com', firstname: 'John', company: 'Mautic', companyemail: 'mautic@mautic.com', companydescription: 'description of company', companywebsite: 'https://mautic.com'});
    

    Events

    Submit Custom Events

    mt('send', 'event', '', '', '', '', {email: 'my@email.com', firstname: 'John'});