Apps can use the APIs to manage store data and functionality. For example, they can update stock and product prices, change price lists for customers, add new orders, or publish new pages. Over 100 methods are available to automate procedures, integrate with other management systems, or connect to external systems.
Apps can access API methods both with JavaScript and from the server via HTTP.
An app opened in the back office can call API methods directly with JavaScript in its pages. To call methods use the Admin.api() function provided by the Admin SDK.
Calls an API method and returns its response.
| Parameter | Description |
|---|---|
method |
Full method name. |
request |
Request with method parameters. Use null if no parameters are present. |
response |
Method response. |
API calls from JavaScript are asynchronous, meaning Admin.api() returns immediately and the callback (the function passed as the third parameter) is invoked later when the method call completes. You can perform multiple calls one after another without waiting for previous ones to finish, because Open2b queues and executes them in order.
If the response and outcome are not important, you can omit the callback.
The following is an example JavaScript call to the commerce.products.update method to update a product:
Admin.api('commerce.products.update', {
id : 496,
product : {
isVisible: true,
name: { it: 'Nuovo nome', en: 'New name' }
}
}, function(response) {
if ( response.status != 'ok' ) {
alert('Error: '+response.error.description);
return;
}
// done
});
Apps can perform calls from their server to the store server via HTTP. API calls via HTTP have the following characteristics:
Unlike JavaScript, where authentication is handled by the back office in which the app is open, with HTTP you must always include the "X-Secret-Key" header to access private methods or the "X-Public-Key" header to access public methods. For apps published in the Store the key is provided when the app is installed on the store; for other apps you can retrieve it in the back office under "Apps > Edit" by clicking the row for the app.
This example shows a call to the commerce.products.update method, previously shown in the JavaScript version, but this time via HTTP using the
Go
PHP
Java
Python
Ruby
Perl
language:
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
)
func main() {
body, err := json.Marshal(map[string]interface{}{
"id": 3,
"product": map[string]interface{}{
"isVisible": true,
"name": map[string]string{"it": "Nuovo nome", "en": "New name"},
},
})
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", "https://www.store.com/open2b/api/v13/commerce.products.update", bytes.NewReader(body))
if err != nil {
log.Fatal(err)
}
req.Header.Set("X-Secret-Key", "EZMRp7tfDT7JisRlGREU3R00do4nq0BSLHRKToTppOZRiTc75a")
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
result := struct {
Status string
Error struct {
Description string
}
}{}
err = json.NewDecoder(res.Body).Decode(&result)
if err != nil {
log.Fatal(err)
}
if result.Status != "ok" {
log.Printf("Request failed: %s\n", result.Error.Description)
}
}
import org.codehaus.jackson.map.ObjectMapper;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.*;
public class UpdateProduct{
public static void main(String[] args){
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> request = new HashMap<String,Object>();
Map<String,Object> product = new HashMap<String,Object>();
Map<String,String> name = new HashMap<String,String>();
name.put("it", "Nuovo nome");
name.put("en", "New name");
product.put("isVisible", (Boolean)true);
product.put("name", name);
request.put("id",(Integer)3);
request.put("product",product);
String body;
try {
body = mapper.writeValueAsString(request);
} catch (Exception e) {
return;
}
HttpURLConnection connection = null;
URL url;
Map<?,?> result;
try {
url = new URL("https://www.store.com/open2b/api/v13/commerce.products.update");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("X-Secret-Key", "jIG0FzJ4OSpilRikDsVtDVmnuWFxaUT41-238_j24gr37-MI6T1QyrtMeq2V0Yj7");
connection.setRequestProperty("Content-Length", Integer.toString(body.getBytes().length));
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.write(body.getBytes());
writer.flush();
writer.close();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String tmp;
StringBuffer responseBuffer = new StringBuffer();
while((tmp = reader.readLine()) != null) {
responseBuffer.append(tmp);
responseBuffer.append('\r');
}
reader.close();
result = mapper.readValue(responseBuffer.toString(), Map.class);
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
if (connection!=null) {
connection.disconnect();
}
}
if (result.get("status").equals("error")) {
System.out.println("error: "+((Map<?,?>)(result.get("error"))).get("description"));
System.exit(-1);
}
}
}
require 'uri'
require 'net/http'
require 'json'
body = JSON.dump({
"id" => 3,
"product" => {
"isVisible" => 1,
"name" => { "it" => "Nuovo nome", "en" => "New name" },
},
})
uri = URI.parse("https://www.store.com/open2b/api/v13/commerce.products.update")
http = Net::HTTP.new(uri.host,uri.port)
headers = {
"X-Secret-Key" => "EZMRp7tfDT7JisRlGREU3R00do4nq0BSLHRKToTppOZRiTc75a",
"Content-Type" => "application/json; charset=UTF-8",
}
req = Net::HTTP::Post.new(uri.path, initheader = headers)
req.body = body
result = JSON.parse(http.request(req).body)
if result["status"] != "ok"
abort("Request failed: " + result["error"]["description"])
end
import json
import http.client
import sys
connection = http.client.HTTPConnection("www.store.com")
body = json.dumps({
"id" : 3,
"product" : {
"isVisible" : True,
"name" : { "it" : "Nuovo nome", "en" : "New name" },
},
})
headers = {
"X-Secret-Key" : "EZMRp7tfDT7JisRlGREU3R00do4nq0BSLHRKToTppOZRiTc75a",
"Content-Type" : "application/json; charset=UTF-8",
}
connection.request("POST", "/open2b/api/v13/commerce.products.update", body, headers)
response = connection.getresponse().read()
result = json.loads(response.decode("utf-8"))
if result["status"] != "ok":
sys.exit("Request failed: " + result["error"]["description"])
require JSON;
require LWP::UserAgent;
my $json = new JSON();
my $ua = new LWP::UserAgent();
my %headers = (
"X-Secret-Key" => "EZMRp7tfDT7JisRlGREU3R00do4nq0BSLHRKToTppOZRiTc75a",
"Content-Type" => "application/json; charset=UTF-8",
);
my $body = $json->encode({
"id" => 3,
"product" => {
"isVisible" => 1,
"name" => { "it" => "Nuovo nome", "en" => "New name" },
},
});
my $response = $ua->post("https://www.store.com/open2b/api/v13/commerce.products.update", %headers, "Content" => $body);
my $result = $json->decode($response->content());
if ($result->{"status"} ne "ok") {
die("Request failed: ".$result->{"error"}{"description"}."\n");
}
$ch = curl_init();
// POST is used for all calls
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// the method called is specified in the URL
curl_setopt($ch, CURLOPT_URL,
'https://www.store.com/open2b/api/v13/commerce.products.update');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
// the key must be present in every call
'X-Secret-Key: EZMRp7tfDT7JisRlGREU3R00do4nq0BSLHRKToTppOZRiTc75a',
// the content type can be "application/json" or "text/javascript"
'Content-Type: application/json; charset=UTF-8'));
// the request is in JSON format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
'id' => 496,
'product' => array(
'isVisible' => true,
'name' => array( 'it' => 'Nuovo nome', 'en' => 'New name' ),
))));
// the response is in JSON format
$response = json_decode(curl_exec($ch), true);
// the response always contains the execution status
if ( $response['status'] != 'ok' ) {
die("Request failed: ".$response['error']['description']);
}
curl_close($ch);
In the documentation for each method the call is shown both for JavaScript:
Admin SDKAdmin.api('commerce.products.update', request, function(response) { … });
and for HTTP:
HTTP POST/api/v13/commerce.products.update
after which the request and response in JSON format follow. For JavaScript the JSON code corresponds to JavaScript itself; for HTTP it is the code sent in the body of the call without the comments and additional spaces that are present in the documentation.