CiviCRM Developer Guide

The API

CiviCRM has a stable comprehensive API (Application Programming Interface) that can be used to access much of the functionality of CiviCRM. The API is the recommended way for any external programme to interact with CiviCRM.

Why use the API?

If you're not familiar with APIs, you might ask why you would use the API when you could access the core functions (e.g. the BAO files) directly?

The answer is that the API is guaranteed to remain stable between releases, and warn developers well in advance of any changes, where as BAOs offer no such guarantee.

There are two current versions of the API: version 2 and version 3.  Version 2 is present to retain backwards compatibility with older code: it should not be used for new projects. 

Version 3 is one of the seven wonders of CiviCRM.  It is much more consistent than version 2 and has much improved test coverage: it should be used for all new projects.

Learning about (and experimenting with) the API V3

The best place to learn about the API is your own test install of CiviCRM.  Be wary about using the API on your live site because the the API does not ask for confirmation, and therefore you can easily make significant changes to your data.

Each install comes with two tools that are useful for this.  The API parameter list, which shows all available entities which can be manipulated by the API and is available at http://[CIVICRM_URL]/civicrm/api/doc, and the API explorer, which is available at http://[CIVICRM_URL]/civicrm/api/explorer.

How to use the API

There are at least 5 different ways of using an API function:

  1. as a php function, to run your own code on the same server as CiviCRM 
  2. via the AJAX interface, to be called from JavaScript code
  3. via the REST* interface, can be called from another server via http calls
  4. as a Smarty function to add data to templates 
  5. from drush on the command line for Drupal installations. 

Calling the API in PHP 

If you write custom code that is going to run within the same environment as CiviCRM, calling the API as a PHP function is the recommended way of modifying or fetching data. You will see examples of API calls throughout the developer documentation. For example, you could create several tags from a script rather than doing it manually from the CiviCRM admin page. The code below shows you how to do it using the API. 

The recommended way to call the API in PHP is

require_once 'api/api.php';
$result = civicrm_api ($entity,$action,$params);

where $entity is the object you want to manipulate (a contact, a tag, a group, a relationship), and$action is get (to retrieve a list or a single entity), create (to create or update if you provide the id), delete, update and getFields (that provide the list of fields of this entity, including the custom fields).

So with real data:

require_once 'api/api.php';
$contact = civicrm_api('Contact','Get',array('first_name' => 'Michael', 'last_name' => 'McAndrew', 'version' =>3));

Calling the API from smarty

CiviCRM defines a smarty function {crmAPI} which can be used to call the API from the template layer.

{crmAPI var="ContactS" entity="Contact" action="get" version="3" first_name="Michael" first_name="McAndrew" }
{foreach from=$ContactS.values item=Contact}
<li>{$Contact.example}</li>
{/foreach}

Calling the API via javascript

It also defines a javascript function crmAPI() which can be used to call the API from javascript. 

 $().crmAPI ('Contact','get',{'version' :'3', 'first_name' :'Michael', 'first_name' :'McAndrew'}}
,{ success:function (data){
$.each(data, function(key, value) {// do something });
}
});

Calling the API via Ajax or REST

You can also call the API via Ajax or REST.  Have a look at the api explorer for examples of how you call the API with these methods.

Calling the API from an external server via the REST API

The syntax and principle are identical to the other methods, but with one major difference: the external server needs to authenticate itself before being able to use any API functions.

To call the API with a browser, use:

http://www.example.org/path/to/civi/codebase/civicrm/extern/rest.php?q=civicrm/<function>

The first call is to authenticate the caller on the CiviCRM server:

https://eg.org/path/to/civi/codebase/civicrm/extern/rest.php?q=civicrm
   /login&name=user&pass=password&key=yoursitekey&json=1

The key is in the CIVICRM_SITE_KEY variable defined in your civicrm.settings.php file.

Note: On the first call, you might get an error message like "This user does not have a valid API key in the database, and therefore cannot authenticate through this interface". This means that you need to generate a key for the user, and add it to the api_key field in the civicrm_contact table in the database.

{"is_error":0,"api_key":"as-in-your-setting.civicrm.php",
   "PHPSESSID":"4984783cb5ca0d51a622ff35fb32b590",
   "key": "2e554f49c9fc5c47548da4b24da64681b77dca08"}

It returns a session id. You can then use any API adding the extra param PHPSESSID = the value returned by the log-in call.

For example:

http://www.example.org/civicrm/ajax/rest?fnName=civicrm/contact/search&json=1&key=
yoursitekey&PHPSESSID=4984783cb5ca0d51a622ff35fb32b590

Note: An action that modifies the database (such as creating a contact or group) should have the parameters passed as POST, not GET. The REST interface accepts both a GET and a POST, but you should follow the web standard and use POST for things that alter the database. You'll win the respect of your peers and the admiration of your friends and family.

Autocomplete and search contacts (API v2)

Note that the instructions below are for API v2.  

If you create a profile for individual contacts that contains the current employer, you might want to add an autocomplete on that field, such as you have on the normal contact edit form. When a user starts to type the name of the current employer, the system will attempt to autocomplete the name from your database of organisation contacts. 

For security reasons, the Ajax interface is restricted to users who have access to CiviCRM - otherwise, it would be fairly easy for anyone to download all the contacts you have in your database. So that's the first thing we check for here: 

{if $session->get('userID') > 0}

<script type="text/javascript" src="/civicrm/{$config->resourceBase}js/rest.js"></script>{literal}
<script>
jQuery(document).ready(function($){
  $('#current_employer').crmAutocomplete({params:{contact_type:'Organization'}});
});
</script>
{/literal}

{/if}

You might want to add additional filters. For instance in a profile "new volunteer from a member", you want to populate the list only with the organisations that belong to the group "members" (group id 42).

$('#current_employer').crmAutocomplete({params:{contact_type:'Organization',group:42}});

Extending the API

It should be noted that it's extremely easy to extend the api if you want to add some funky features: add a Magic.php file under api/v3, create a function civicrm_magic_getpony and voila, you have civicrm_api ("magic","getpony"), the smarty, the ajax, the REST, and it's also directly usable from the api explorer at /civicrm/ajax/doc