Difference between revisions of "Module Web Services API REST (developer)"
(ajout d'explications et d'exemples de code) |
(mise en page) |
||
Line 50: | Line 50: | ||
To install, open the modules page and activate de API REST module. On the configuration page of the module, There's two links. No need to click on the first, it doesnt work as is. | To install, open the modules page and activate de API REST module. On the configuration page of the module, There's two links. No need to click on the first, it doesnt work as is. | ||
− | The link has this pattern = http://<my server>/api/index.php/login?login=<user login>&password=yourpassword | + | The link has this pattern = <nowiki>http://<my server>/api/index.php/login?login=<user login>&password=yourpassword</nowiki><br/> |
− | copy the link and replace yourpassword by your user password. <my server> and <user login> should have been already replaced. Past the link in your browser to generate your <token>. This token is linked to the user account. | + | copy the link and replace yourpassword by your user password. <my server> and <user login> should have been already replaced. Past the link in your browser to generate your <token>. This token is linked to the user account.<br/> |
Write down this <token> as you will need it later !!! | Write down this <token> as you will need it later !!! | ||
− | Now, You can use the second link on the configuration page of the module. On the top right corner, paste your <token> and click the "explore" button. You should see all the actions available with this token. If you don't have a lot of actions, it's probably because the according modules are not activated. If you want to see the invoices, you have to activate the invoice module in the configuration of Dolibarr. Same for products, thirsparties and so on. | + | Now, You can use the second link on the configuration page of the module. On the top right corner, paste your <token> and click the "explore" button. You should see all the actions available with this token. If you don't have a lot of actions, it's probably because the according modules are not activated. If you want to see the invoices, you have to activate the invoice module in the configuration of Dolibarr. Same for products, thirsparties and so on.<br/> |
On this exploration page of the API, you can do quite a lot of tests. Reading datas from Dolibarr and writing, modifying and deleting as well. | On this exploration page of the API, you can do quite a lot of tests. Reading datas from Dolibarr and writing, modifying and deleting as well. | ||
− | |||
= Use = | = Use = | ||
− | To use the REST API, you have to call an url such as this one : http://<my_server>/api/index.php/<action> | + | To use the REST API, you have to call an url such as this one : <nowiki>http://<my_server>/api/index.php/<action></nowiki><br/> |
− | with one of the 4 following methods : GET, POST, PUT, DELETE, replacing <action> by the action you want to use. Ex : http://<my_server>/api/index.php/invoices | + | with one of the 4 following methods : GET, POST, PUT, DELETE, replacing <action> by the action you want to use. Ex : <nowiki>http://<my_server>/api/index.php/invoices</nowiki> |
There's different ways to do so. Here's a piece of code but you can also use libraries such as phphttpclient.com | There's different ways to do so. Here's a piece of code but you can also use libraries such as phphttpclient.com | ||
− | < | + | <source lang="php">function CallAPI($method, $apikey, $url, $data = false) |
{ | { | ||
$curl = curl_init(); | $curl = curl_init(); | ||
Line 109: | Line 108: | ||
return $result; | return $result; | ||
− | }</ | + | }</source> |
− | This is just a working example. There's no error control and security was not in mind but you can use this code, modify it to suit your needs | + | This is just a working example. There's no error control and security was not in mind but you can use this code, modify it to suit your needs<br/> |
The fonction has 4 parameters : | The fonction has 4 parameters : | ||
− | $method : string, "GET", "POST", "PUT", "DELETE" | + | * $method : string, "GET", "POST", "PUT", "DELETE" |
− | $apikey : string, "your <token> generated earlier" | + | * $apikey : string, "your <token> generated earlier" |
− | $url : string, url to call. Ex : "http://<my_server>/api/index.php/invoices" | + | * $url : string, url to call. Ex : "<nowiki>http://<my_server>/api/index.php/invoices</nowiki>" |
− | $data : string, datas in json format. This parameter is not mandatory. | + | * $data : string, datas in json format. This parameter is not mandatory. |
= Examples = | = Examples = | ||
Line 123: | Line 122: | ||
Now, some examples. | Now, some examples. | ||
in every examples, | in every examples, | ||
− | + | * $apiKey = "my <token>"; | |
− | + | * $apiUrl = "<nowiki>http://<my_server>/api/index.php/</nowiki>"; | |
+ | <source lang="php"> | ||
// Retrieve products list | // Retrieve products list | ||
$listProduits = []; | $listProduits = []; | ||
Line 138: | Line 138: | ||
} | } | ||
} | } | ||
+ | </source> | ||
+ | Comments : | ||
+ | * I retrieve the 10'000 first products sorted on their ID in the base | ||
+ | * html_entity_decode is necessary as single quotes are encoded | ||
+ | * It's easy to use the same method (replacing products with dictionnarycountries) to retrieve the list of countries and their ID | ||
− | |||
− | |||
− | |||
− | |||
+ | <source lang="php"> | ||
// Create a product | // Create a product | ||
$ref = "my_product_ref_X203ZZ"; | $ref = "my_product_ref_X203ZZ"; | ||
Line 152: | Line 154: | ||
$newProductResult = CallAPI("POST", $apiKey, $apiUrl."products", json_encode($newProduct)); | $newProductResult = CallAPI("POST", $apiKey, $apiUrl."products", json_encode($newProduct)); | ||
$newProductResult = json_decode($newProductResult, true); | $newProductResult = json_decode($newProductResult, true); | ||
+ | </source> | ||
+ | Comments : | ||
+ | * before cerating a product, it could be wise to check if it exists. Using my first example, you'll have : | ||
− | |||
− | |||
+ | <source lang="php"> | ||
// my ref | // my ref | ||
$ref = "my_product_ref_X203ZZ"; | $ref = "my_product_ref_X203ZZ"; | ||
Line 182: | Line 186: | ||
} | } | ||
} | } | ||
+ | </source> | ||
+ | Comments : | ||
+ | * I check if the ref of my product exist in the array created in the first example. | ||
+ | * If it exists, I use it's key in the array as ID | ||
+ | * If it doesn't exist, I create the product, then I add it to my array for next time then I use the ID created | ||
+ | * I choose this method to do less API calls when I have to import 500 orders. I just need to retrieve the products list once at the beginning instead of searching Dolibarr each time. | ||
− | |||
− | |||
− | |||
− | |||
− | |||
+ | <source lang="php"> | ||
// create an order with 2 products | // create an order with 2 products | ||
Line 232: | Line 238: | ||
$newCommandeResult = json_decode($newCommandeResult, true); | $newCommandeResult = json_decode($newCommandeResult, true); | ||
} | } | ||
+ | </source> | ||
+ | Comments : | ||
+ | * $clientDoliId is the ID of the customer in the Dolibarr database. Either you know it or you can search for it before | ||
+ | * type => 0, This is a customer order (while 1 = supplier order) | ||
− | |||
− | |||
− | |||
+ | <source lang="php"> | ||
// Validate an order | // Validate an order | ||
$newCommandeValider = [ | $newCommandeValider = [ | ||
Line 245: | Line 253: | ||
$newCommandeValiderResult = json_decode($newCommandeValiderResult, true); | $newCommandeValiderResult = json_decode($newCommandeValiderResult, true); | ||
+ | </source> | ||
Comments : | Comments : | ||
− | + | * in this example, on the penultimate line, we can see : $apiUrl."orders/".$newCommandeResult."/validate".<br/> | |
$newCommandeResult is the ID of the order created in the previous example | $newCommandeResult is the ID of the order created in the previous example | ||
+ | |||
+ | <source lang="php"> | ||
// search in the database if a customer exist | // search in the database if a customer exist | ||
$customer_name = "Acme Inc"; | $customer_name = "Acme Inc"; | ||
Line 260: | Line 271: | ||
) | ) | ||
), true); | ), true); | ||
+ | </source> | ||
+ | Comments : | ||
+ | * limit => 1 only 1 customer | ||
+ | * mode => 1 we are looking for a customer, not a supplier (they are thirdparties too but with a different status) | ||
+ | * sqlfilters a bit special but there are more examples on the explorer page | ||
− | |||
− | |||
− | |||
− | |||
+ | <source lang="php"> | ||
// customer doesn't exist. Let's create it and get it's ID | // customer doesn't exist. Let's create it and get it's ID | ||
$newClient = [ | $newClient = [ | ||
Line 276: | Line 289: | ||
$newClientResult = json_decode($newClientResult, true); | $newClientResult = json_decode($newClientResult, true); | ||
$clientDoliId = $newClientResult; | $clientDoliId = $newClientResult; | ||
− | + | </source> | |
Comments : | Comments : | ||
− | + | * client => 1 He is a customer (not a supplier) | |
− | + | * code_client => -1 so the customer code will be generated automatically. | |
− | + | * we get the customer ID in $clientDoliId | |
= Conclusion = | = Conclusion = | ||
− | this are just the basics. | + | this are just the basics.<br/> |
− | Some more informations in the dolibarr code. You can look here : htdocs/<directory>/class/api_xxx_class.php | + | Some more informations in the dolibarr code. You can look here : htdocs/<directory>/class/api_xxx_class.php<br/> |
− | Ex : htdocs/societe/class/api_thirdparties.class.php for thirdparties. | + | Ex : htdocs/societe/class/api_thirdparties.class.php for thirdparties.<br/> |
Invoices are in htdocs/compta/facture/class | Invoices are in htdocs/compta/facture/class |
Revision as of 17:29, 23 May 2017
Web services | |
---|---|
Numero/ID of module | 2610 |
User doc. of module | Not applicable |
Developer doc. of module | This page |
Function
When enabling this module, you enable usage of web services provided by Dolibarr server. You can then make REST call of different web services provided by Dolibarr.
Dolibarr REST web services server
Once module webservices REST is activated, Dolibarr become also a server of REST web services. So you can send your own REST request to relative URL /api/index.php
List of provided services
Only few services are available. Starting to Dolibarr 5.0 version, you can see full list of Dolibarr Webservices provided, by calling the explorer here at address:
http://yourdolibarrurl/api/index.php/explorer.
You must first make the first call to the login api to get the api key. Then enter api key to get list of all other available services.
For example, you can try the explorer on the demo instance at:
https://demo.dolibarr.org/api/index.php/explorer
You must first make the first call to the login api to get the api key. Then enter api key to get list of all other available services.
Adding a new service
Adding a new REST service is as easy than adding a file called api_mymoduleobject.class.php into the directory htdocs/module/class. You take the example into htdocs/commande/class/api_orders.class.php
The framework detects automatically the API and it should be visible into the explorer.
Method and parameters are detected according to introspection done into PHP class of the object (htdocs/module/class/object.class.php) using the annotations found into the class. For a documentation about annotation: https://github.com/Luracast/Restler/blob/master/ANNOTATIONS.md
Installation
To install, open the modules page and activate de API REST module. On the configuration page of the module, There's two links. No need to click on the first, it doesnt work as is.
The link has this pattern = http://<my server>/api/index.php/login?login=<user login>&password=yourpassword
copy the link and replace yourpassword by your user password. <my server> and <user login> should have been already replaced. Past the link in your browser to generate your <token>. This token is linked to the user account.
Write down this <token> as you will need it later !!!
Now, You can use the second link on the configuration page of the module. On the top right corner, paste your <token> and click the "explore" button. You should see all the actions available with this token. If you don't have a lot of actions, it's probably because the according modules are not activated. If you want to see the invoices, you have to activate the invoice module in the configuration of Dolibarr. Same for products, thirsparties and so on.
On this exploration page of the API, you can do quite a lot of tests. Reading datas from Dolibarr and writing, modifying and deleting as well.
Use
To use the REST API, you have to call an url such as this one : http://<my_server>/api/index.php/<action>
with one of the 4 following methods : GET, POST, PUT, DELETE, replacing <action> by the action you want to use. Ex : http://<my_server>/api/index.php/invoices
There's different ways to do so. Here's a piece of code but you can also use libraries such as phphttpclient.com
function CallAPI($method, $apikey, $url, $data = false)
{
$curl = curl_init();
$httpheader = ['DOLAPIKEY: '.$apikey];
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
$httpheader[] = "Content-Type:application/json";
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
$httpheader[] = "Content-Type:application/json";
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
// curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $httpheader);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
This is just a working example. There's no error control and security was not in mind but you can use this code, modify it to suit your needs
The fonction has 4 parameters :
- $method : string, "GET", "POST", "PUT", "DELETE"
- $apikey : string, "your <token> generated earlier"
- $url : string, url to call. Ex : "http://<my_server>/api/index.php/invoices"
- $data : string, datas in json format. This parameter is not mandatory.
Examples
Now, some examples. in every examples,
- $apiKey = "my <token>";
- $apiUrl = "http://<my_server>/api/index.php/";
// Retrieve products list
$listProduits = [];
$produitParam = ["limit" => 10000, "sortfield" => "rowid"];
$listProduitsResult = CallAPI("GET", $apiKey, $apiUrl."products", $produitParam);
$listProduitsResult = json_decode($listProduitsResult, true);
if (isset($listProduitsResult["error"]) && $listProduitsResult["error"]["code"] >= "300") {
} else {
foreach ($listProduitsResult as $produit) {
$listProduits[intval($produit["id"])] = html_entity_decode($produit["ref"], ENT_QUOTES);
}
}
Comments :
- I retrieve the 10'000 first products sorted on their ID in the base
- html_entity_decode is necessary as single quotes are encoded
- It's easy to use the same method (replacing products with dictionnarycountries) to retrieve the list of countries and their ID
// Create a product
$ref = "my_product_ref_X203ZZ";
$newProduct = [
"ref" => $ref,
"label" => $ref
];
$newProductResult = CallAPI("POST", $apiKey, $apiUrl."products", json_encode($newProduct));
$newProductResult = json_decode($newProductResult, true);
Comments :
- before cerating a product, it could be wise to check if it exists. Using my first example, you'll have :
// my ref
$ref = "my_product_ref_X203ZZ";
// does it exist in my array
$produitKey = array_search($ref, $listProduits);
if ($produitKey) {
// yes
$fk_product = $produitKey;
} else {
// no
// Create the product
$newProduct = [
"ref" => $ref,
"label" => $ref
];
$newProductResult = CallAPI("POST", $apiKey, $apiUrl."products", json_encode($newProduct));
$newProductResult = json_decode($newProductResult, true);
if (isset($newProductResult["error"]) && $newProductResult["error"]["code"] >= "300") {
// there's been an error
echo "<pre>ERROR", var_dump($newProductResult), "</pre>";
exit;
} else {
// everything good
$fk_product = $newProductResult;
$listProduits[$fk_product] = $ref;
}
}
Comments :
- I check if the ref of my product exist in the array created in the first example.
- If it exists, I use it's key in the array as ID
- If it doesn't exist, I create the product, then I add it to my array for next time then I use the ID created
- I choose this method to do less API calls when I have to import 500 orders. I just need to retrieve the products list once at the beginning instead of searching Dolibarr each time.
// create an order with 2 products
// The array where there will be all the products lines of my order.
$newCommandeLine = [];
// product 1
$ref1 = "my_product_ref_X203ZZ";
$prix1 = 10;
$qtt1 = 100;
$tva1 = 20;
$fk_product1
// product 2
$ref2 = "my_product_ref_B707FD";
$prix2 = 13;
$qtt2 = 37;
$tva2 = 20;
$newCommandeLine[] = [
"desc" => $ref1,
"subprice" => $prix1,
"qty" => $qtt1,
"tva_tx" => floatval($tva1),
"fk_product"=> $fk_product1
];
$newCommandeLine[] = [
"desc" => $ref2,
"subprice" => $prix2,
"qty" => $qtt2,
"tva_tx" => floatval($tva2),
"fk_product"=> $fk_product2
];
if (count($newCommandeLine) > 0) {
$newCommande = [
"socid" => $clientDoliId,
"type" => "0",
"lines" => $newCommandeLine,
"note_private" => "order created automatically with API",
];
$newCommandeResult = CallAPI("POST", $apiKey, $apiUrl."orders", json_encode($newCommande));
$newCommandeResult = json_decode($newCommandeResult, true);
}
Comments :
- $clientDoliId is the ID of the customer in the Dolibarr database. Either you know it or you can search for it before
- type => 0, This is a customer order (while 1 = supplier order)
// Validate an order
$newCommandeValider = [
"idwarehouse" => "0",
"notrigger" => "0"
];
$newCommandeValiderResult = CallAPI("POST", $apiKey, $apiUrl."orders/".$newCommandeResult."/validate", json_encode($newCommandeValider));
$newCommandeValiderResult = json_decode($newCommandeValiderResult, true);
Comments :
- in this example, on the penultimate line, we can see : $apiUrl."orders/".$newCommandeResult."/validate".
$newCommandeResult is the ID of the order created in the previous example
// search in the database if a customer exist
$customer_name = "Acme Inc";
$clientSearch = json_decode(CallAPI("GET", $apiKey, $apiUrl."thirdparties", array(
"sortfield" => "t.rowid",
"sortorder" => "ASC",
"limit" => "1",
"mode" => "1",
"sqlfilters" => "(t.nom:=:'".$customer_name."')"
)
), true);
Comments :
- limit => 1 only 1 customer
- mode => 1 we are looking for a customer, not a supplier (they are thirdparties too but with a different status)
- sqlfilters a bit special but there are more examples on the explorer page
// customer doesn't exist. Let's create it and get it's ID
$newClient = [
"name" => "customer company name",
"email" => "customer company email",
"client" => "1",
"code_client" => "-1"
];
$newClientResult = CallAPI("POST", $apiKey, $apiUrl."thirdparties", json_encode($newClient));
$newClientResult = json_decode($newClientResult, true);
$clientDoliId = $newClientResult;
Comments :
- client => 1 He is a customer (not a supplier)
- code_client => -1 so the customer code will be generated automatically.
- we get the customer ID in $clientDoliId
Conclusion
this are just the basics.
Some more informations in the dolibarr code. You can look here : htdocs/<directory>/class/api_xxx_class.php
Ex : htdocs/societe/class/api_thirdparties.class.php for thirdparties.
Invoices are in htdocs/compta/facture/class