Skip to content
Snippets Groups Projects
Unverified Commit 45387a16 authored by Seamus Lee's avatar Seamus Lee Committed by GitHub
Browse files

Merge pull request #690 from seamuslee001/apiv4_documentation

Apiv4 documentation
parents bd2652a3 16bc31f8
No related branches found
No related tags found
No related merge requests found
# The CiviCRM API # The CiviCRM API
CiviCRM has a stable comprehensive **API** (Application Programming CiviCRM has a stable comprehensive **API** (Application Programming Interface) that can be used to access and manage data in CiviCRM. The API is the recommended way for any CiviCRM extension, CMS module, or external program to interact with CiviCRM.
Interface) that can be used to access and manage data in CiviCRM. The
API is the recommended way for any CiviCRM extension, CMS module, or Utilizing the API is superior to accessing core functions directly (e.g.calling raw SQL, or calling functions within the BAO files) because the API offers a consistent interface to CiviCRM's features. It is designed to function predictably with every new release so as to preserve backwards compatibility of the API for several versions of CiviCRM. If you decide to use other ways to collect data (like your own SQL statements), you risk running into future problems when changes to the schema and BAO arguments inevitably occur.
external program to interact with CiviCRM.
The best place to begin working with the API is your own *test* install of CiviCRM, using the API explorer and the API parameter list.
Utilizing the API is superior to accessing core functions directly (e.g.
calling raw SQL, or calling functions within the BAO files)
because the API offers a consistent interface to CiviCRM's features. It is
designed to function predictably with every new release so as to preserve
backwards compatibility of the API for several versions of CiviCRM. If
you decide to use other ways to collect data (like your own SQL statements),
you risk running into future problems when changes to the schema and
BAO arguments inevitably occur.
The best place to begin working with the API is your own ***test*** install of
CiviCRM, using the API explorer and the API parameter list.
For help creating your own API custom calls, see [civix generate:api](/extensions/civix.md#generate-api) For help creating your own API custom calls, see [civix generate:api](/extensions/civix.md#generate-api)
...@@ -23,29 +12,30 @@ For help creating your own API custom calls, see [civix generate:api](/extension ...@@ -23,29 +12,30 @@ For help creating your own API custom calls, see [civix generate:api](/extension
The API explorer is a powerful GUI tool for building and executing API calls. The API explorer is a powerful GUI tool for building and executing API calls.
To access the API explorer: ### Access the APIv3 explorer:
1. Go to any CiviCRM site
* This can even be the [demo site](http://dmaster.demo.civicrm.org/).
1. Within the CivCRM menu, go to **Support > Developer > APIv3 Explorer** or go to the URL `/civicrm/api`.
### Access the APIv4 explorer:
1. Go to any CiviCRM site 1. Go to any CiviCRM site
* This can even be the [demo site](http://dmaster.demo.civicrm.org/). * This can even be the [demo site](http://dmaster.demo.civicrm.org/).
1. Within the CivCRM menu, go to **Support > Developer > API Explorer** or go to the URL `/civicrm/api`. 1. Within the CivCRM menu, go to **Support > Developer > APIv4 Explorer** or go to the URL `/civicrm/api4`.
!!! warning !!! warning
The API explorer actually executes real API calls. It can modify data! So if you execute a `Contact` `delete` call, it will really delete the contact. As such, any experimenting is best done within a test site. The API explorer actually executes real API calls. It can modify data! So if you execute a `Contact` `delete` call, it will really delete the contact. As such, any experimenting is best done within a test site.
You can select the entity you want to You can select the entity you want to use, for example `Contact` and the action you want to perform, for example `Get`. The API explorer will show you the specific code necessary to execute the API call you have been testing using the various API interfaces available.
use, for example `Contact` and the action you want to perform, for
example `Get`. The API explorer
will show you the specific code necessary to execute the API call you
have been testing.
## API parameter documentation ## API parameter documentation
From the API explorer, you can click on the **Code Docs** tab to find documentation for each API entity/action. You will first get a list of all the API entities. If you click on an entity you will get a list of parameters that are available for that specific entity, with the type of the parameter. This can be very useful if you want to check what you can retrieve with the API and what parameters you can use to refine your get From the API explorer, you can get documentation on how to construct your API query. This is done either in the screen as you fill out the GUI to create your API call or in the v3 Explorer there are docs under the Code Docs tab which will point at the relevant aspects of the v3 code base that run the API calls.
action or complete your create or update action.
## API examples ## API examples
From the API explorer, you can click on the **Examples** tab to find examples of API calls which are based on automated tests within the source code. You can also [explore these examples on GitHub](https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples). Within the API Explorer you will be able to attain an example of the code that you should write to call the API. In APIv3, you can also access epscific examples of some API calls from the Examples tab within the explorer. You can also [explore these examples on GitHub](https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples).
### API Examples in your extensions ### API Examples in your extensions
......
# APIv3 Interfaces # API Interfaces
The APIv3 has three main interfaces along with the PHP Code that can be used to access the API. The API has three main interfaces along with the PHP Code that can be used to access the API.
## Javascript {#javascript} ## Javascript {#javascript}
...@@ -10,56 +10,9 @@ CiviCRM provides a number of different methods to interact with the API when in ...@@ -10,56 +10,9 @@ CiviCRM provides a number of different methods to interact with the API when in
The AJAX interface is one of the more common interfaces used within CiviCRM code. The AJAX interface is most commonly seen when used in javascript code. You can get example AJAX interface code out of the [API Explorer](/api/index.md#api-explorer) as needed. The AJAX interface is one of the more common interfaces used within CiviCRM code. The AJAX interface is most commonly seen when used in javascript code. You can get example AJAX interface code out of the [API Explorer](/api/index.md#api-explorer) as needed.
#### CRM.api3 #### CRM.api3 / CRM.api4
`CRM.api3` is a javascript method produced by CiviCRM as a thin wrapper around a call to `http://example.org/civicrm/ajax/rest`. The standard format of a `CRM.api3` call would be
```javascript
CRM.api3('entity', 'action', [params], [statusMessage]);
```
If you pass `true` in as the `StatusMessage` param, it will display the default status Message. This is useful when doing things such as adding tags to contacts or similar. If you wish to do further work based on the result of the API call (e.g use the results from a GET call) you will need to use the [done method](http://api.jquery.com/deferred.done/) to listen for the event. For example:
```javascript
CRM.api3('entity_tag', 'create', {contact_id:123, tag_id:42})
.done(function(result) {
console.log(result);
});
```
Using the CRM.api3 method you can pass multiple requests through at once e.g.
```javascript
var params = [
['email', 'get', {contact_id: 123}],
['phone', 'get', {phone: '555-5555'}]
];
CRM.api3(params).done(function(result) {
console.log('email result is:', result[0]);
console.log('phone result is:', result[1]);
});
```
You can also use associative objects in your API call as follows:
```
var params = {
one: ['email', 'getoptions', {field: 'location_type_id'}],
two: ['phone', 'getoptions', {field: 'phone_type_id', sequential: 1}],
three: ['phone', 'get']
};
CRM.api3(params).done(function(result) {
console.log('email result is:', result.one);
console.log('phone options are:', result.two);
console.log('phone get result is:', result.three);
});
```
These requests are different to doing a Chained API call as they are making simultaneous API requests and they are not related or dependent on each other.
!!! note
Javascript does not guarantee the *ordering* of associative objects. To ensure the API calls execute in a specific order, use the array syntax instead.
`CRM.api3` and `CRM.api4` is a javascript method produced by CiviCRM as a thin wrapper around a call to `http://example.org/civicrm/ajax/rest`. The standard format of such an API call can be found under the relevant usage sub-chapter of this documentation
#### Tests #### Tests
......
...@@ -161,20 +161,48 @@ For more details, see [REST interface](/api/interfaces.md#rest).  ...@@ -161,20 +161,48 @@ For more details, see [REST interface](/api/interfaces.md#rest). 
CRM.api3('entity', 'action', [params], [statusMessage]); CRM.api3('entity', 'action', [params], [statusMessage]);
``` ```
For more details, see [AJAX Interface](/api/interfaces.md#ajax). If you pass `true` in as the `StatusMessage` param, it will display the default status message. This is useful when doing things such as adding tags to contacts or similar. If you wish to do further work based on the result of the API call (e.g use the results from a GET call) you will need to use the [done method](http://api.jquery.com/deferred.done/) to listen for the event. For example:
The AJAX interface is automatically available for web-pages generated through ```javascript
CiviCRM (such as standard CiviCRM web-pages, CiviCRM extensions, CRM.api3('entity_tag', 'create', {contact_id:123, tag_id:42})
and custom CiviCRM templates). .done(function(result) {
console.log(result);
The AJAX interface could be made available to other parts of the same website });
(e.g. a drupal module or wordpress widget) by calling ```
`CRM_Core_Resources::singleton()->addCoreResources()`
from php. Please note that the AJAX interface is subject to Using the CRM.api3 method you can pass multiple requests through at once e.g.
[API Security](/security/permissions.md#api-permissions)
and ```javascript
[Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy). var params = [
To use it from an external site or application, see REST interface documentation. ['email', 'get', {contact_id: 123}],
['phone', 'get', {phone: '555-5555'}]
];
CRM.api3(params).done(function(result) {
console.log('email result is:', result[0]);
console.log('phone result is:', result[1]);
});
```
You can also use associative objects in your API call as follows:
``` javascript
var params = {
one: ['email', 'getoptions', {field: 'location_type_id'}],
two: ['phone', 'getoptions', {field: 'phone_type_id', sequential: 1}],
three: ['phone', 'get']
};
CRM.api3(params).done(function(result) {
console.log('email result is:', result.one);
console.log('phone options are:', result.two);
console.log('phone get result is:', result.three);
});
```
The AJAX interface is automatically available for web-pages generated through CiviCRM (such as standard CiviCRM web-pages, CiviCRM extensions and custom CiviCRM templates).
The AJAX interface could be made available to other parts of the same website (e.g. a Drupal module or WordPress widget) by calling `CRM_Core_Resources::singleton()->addCoreResources()`
from php. Please note that the AJAX interface is subject to [API Security](/security/permissions.md#api-permissions)
and [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy). To use it from an external site or application, see the REST interface documentation.
## Smarty ## Smarty
......
# APIv4 Usage
Every API call consists of three elements: the *entity*, *action*, and *parameters*. For example, consider a few commonly-used entities along with the supported actions and parameters:
(*For full, up-to-date details about specific entities and parameters, use the [API Explorer](/api/index.md#api-explorer).*)
The API is available in many different environments (such as PHP, REST, and Javascript), and the notation differs slightly in each environment.
However, if you understand the canonical notation, then other environments will appear as small adaptations.
Canonically, an API call is processed by the API kernel. The `$entity`, `$action`, and `$params` are passed as inputs, and an arrayObject is returned as output.
A couple of significant differences between APIv4 and APIv3 is that in v4 the `check_permissions` flag is set to true by default and on get actions especially but more generally the limit of 25 items returned that v3 has has been removed in favour of coders specifying the limit if they want to in their code calls.
```php
$result = Civi::service('civi_api_kernel')->run('Contact', 'get', [
'version' => 4,
'where' => [
['first_name', '=', 'Alice'],
['last_name', '=', 'Roberts'],
],
]);
```
The result of a successful API call typically looks like this:
```php
[
{ /* DAO Object */ }
]
```
The result of a failed API call typically looks like this:
```php
array(
'is_error' => 1,
'error_message' => /* a descriptive error message */,
)
```
!!! note
A few specialized actions like `getsingle` or `getvalue` may return success in a different format.
## PHP
This is the most common way to call the API. There are 2 formats of API calls a procedural approach and the more traditional approach
Object Oriented Procedural approach:
```php
$contacts = \Civi\Api4\Contact::get()
->addWhere('last_name', '=', 'Adams')
->setLimit(25)
->execute();
```
Note that we use the a format of Object::action and then there are helper functions like AddWhere
```php
try {
$contacts = civicrm_api4('Contact', 'get', array(
'where' => [
['first_name', '=', 'Alice'],
['last_name', '=', 'Roberts'],
],
]);
}
catch (\API_Exception $e) {
$error = $e->getMessage();
}
printf("Found %d item(s)\n", count($contacts));
```
This format matches canonical format almost exactly, with a few improvements for usability:
- The `version => 4` parameter is not required.
- Errors are reported as PHP exceptions. You may catch the exceptions or (by default) allow them to bubble up.
- You can immediately iterate over the contacts returned
*Note*: If you're writing a Drupal module, a Joomla extension, a WordPress plugin, or a standalone script, then you may need to **bootstrap** CiviCRM before using the API. See the examples in [Bootstrap Reference](/framework/bootstrap.md).
## REST
To be implemented
## AJAX
```javascript
CRM.api4('entity', 'action', [params], [statusMessage]);
```
If you pass `true` in as the `StatusMessage` param, it will display the default Status Message. This is useful when doing things such as adding tags to contacts or similar. If you wish to do further work based on the result of the API call (e.g use the results from a GET call) you will need to use the [done method](http://api.jquery.com/deferred.done/) to listen for the event. For example:
```javascript
CRM.api4('EntityTag', 'create', {
values: {"entity_id":5, "tag_id":3}
}).then(function(results) {
// do something with results array
}, function(failure) {
// handle failure
});
```
The AJAX interface is automatically available for web-pages generated through CiviCRM (such as standard CiviCRM web-pages, CiviCRM extensions and custom CiviCRM templates).
The AJAX interface could be made available to other parts of the same website (e.g. a Drupal module or WordPress widget) by calling `CRM_Core_Resources::singleton()->addCoreResources()`
from php. Please note that the AJAX interface is subject to [API Security](/security/permissions.md#api-permissions)
and [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy). To use it from an external site or application, see REST interface documentation.
## Smarty
## Scheduled jobs
Any API call can be configured to be run as a scheduled job. These can be configured in the UI under **Administer -> System Settings -> Scheduled Jobs**. Usually API calls run this way are written with the intent that they be run as scheduled jobs - e.g those with the Job entity or provided by payment processors to run recurring payments.
## Command line
### drush
To be Implemented
### wp-cli
To be Implemented
### cv
```bash
cv api4 Contact.get '{"where":[["first_name", "=", "Alice"], ["last_name", "=", "Roberts"]]}'
```
## API Security
API has security measures built in depending on the way the API is called that can also be turned off or on. API Permissions are also able to be altered via hook. More information on API Security can be found in the [Security Documentation](/security/permissions.md).
...@@ -48,8 +48,8 @@ pages: ...@@ -48,8 +48,8 @@ pages:
- API: - API:
- API Intro: api/index.md - API Intro: api/index.md
- API Interfaces: api/interfaces.md - API Interfaces: api/interfaces.md
#- APIv4: - APIv4:
# - APIv4 Usage: api/v4/usage.md - APIv4 Usage: api/v4/usage.md
# - APIv4 Actions: api/v4/actions.md # - APIv4 Actions: api/v4/actions.md
# - APIv4 Options: api/v4/options.md # - APIv4 Options: api/v4/options.md
# - APIv4 Joins: api/v4/joins.md # - APIv4 Joins: api/v4/joins.md
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment