Child pages
  • Create APIs
Skip to end of metadata
Go to start of metadata

Create and expose your APIs

As a developer, you may want to reuse some of the logic that you implemented once, in many different applications that you build. You might also want to expose part of this logic as APIs to other developers who will incorporate it into their own applications. Using Apstrata server-side scripts, this is very simple to do, harnessing the simplicity of JavaScript and leveraging the power of Apstrata's APIs.

Apstrata allows you to create your back-end logic using JavaScript scripts running on the server and having native access to all Apstrata's APIs. Moreover, you can decide to expose these scripts as public APIs to third party applications. Upload your script to your Apstrata application using SaveScript API and execute them by invoking the RunScript API.

Back to the map       Next station: orchestrate

Example: the game builder API

Let us assume that you implemented a nice engine for mobile games and that you would like to expose its features to other developers, as APIs. To keep it simple, imagine that, using Apstrata server-side script, you would like to implement an API that creates an initial board for a card matching memory game.

API Excerpt
<script> 
	<scriptACL> <!-- this section determines the execute/read/write authorizations on this script -->
		<execute>authenticated</execute>
		<read>nobody</read>
		<write>nobody</write>
	</scriptACL>
	<code>
		<![CDATA[ 
		    /*
		     * This API builds the board of a card matching memory game. It returns an array 
		     * of shuffled image name pairs. The size of the board is determined by the "level" 
		     * parameter that is retrieved from the HTTP request. The type of images to use 
		     * (fruits or animals) is also retrieved from the "type" request parameter.
		     */		    
		    var level = request.parameters["level"] || "average"; // retrieve the "level" parameter from the request
		    var type = request.parameters["type"] || "fruits"; // retrieve the "type" parameter from the request
		    return buildGameBoard(level, type);
		    
	        function buildGameBoard(gameLevel, imageType) {    
                // build the game board, for now return dummy values
				return ["peach", "banana", "cherry", "cherry", "apricot", "mango", "mango", "lemon", "banana", "apricot", "cherry", "lemon", "lemon", 	"grapes", "lemon", "lemon", "grapes", "lemon", "cherry", "peach"];
            }
		]]>
	</code>
</script>
 Click here to see the full code example
<script>
	<scriptACL>
		<execute>nobody</execute>
		<read>nobody</read>
		<write>nobody</write>
	</scriptACL>
	<code>
		<![CDATA[
		    /*
		     * This API builds the board of a card matching memory game. It returns an array 
		     * of shuffled image name pairs. The size of the board is determined by the "level" 
		     * parameter that is retrieved from the HTTP request. The type of images to use 
		     * (fruits or animals) is also retrieved from the "type" request parameter.
		     */		    
		    var level = request.parameters["level"] || "average"; // retrieve the "level" parameter from the request
		    var type = request.parameters["type"] || "fruits"; // retrieve the "type" parameter from the request
		    return buildGameBoard(level, type);
		    
	        function buildGameBoard(gameLevel, imageType) {    
                var fruits = ["peach", "apricot", "apple", "watermelon", "grapes", "banana", "kiwi", "lemon", "orange", "cherry", "mango", "litchi", "pineapple"];		    
                var animals = ["lion", "zebra", "monkey", "elephant", "giraffe", "tiger", "crocodile", "antelope", "buffalo", "ostrich", "lemur"];
                var levelMap = {
                    "easy": 16,
                    "average": 20,
                    "difficult": 24
                  };        
                var images = imageType == "fruits" ? fruits : animals;
                var pos = 0;
                var cell = {};
                var gameBoard = [];
                var availableLocations = resetAvailableLocations(levelMap[gameLevel]);
                var cell = {};
                var image = "";
                var pos1 = 0;
                var pos2 = 0;
                for (var i = 0; i < levelMap[gameLevel] / 2; i++) {                
                    var index = Math.floor(Math.random() * images.length);
                    image = images[index];
                    var result = getAvailableLocation(availableLocations);
                    availableLocations.splice(result.index, 1);
                    gameBoard[result.location] = image;
                    result = getAvailableLocation(availableLocations);
                    availableLocations.splice(result.index, 1);
                    gameBoard[result.location] = image;
                }            
              return gameBoard;
            }
        
            function resetAvailableLocations(length) {              
              var locations = [];
              for (var i = 0; i < length; i++) {
                locations.push(i);
              }              
              return locations;
            }
        
            function getAvailableLocation(availableLocations) {            
              var index = Math.floor(Math.random() * availableLocations.length);
              return {"index": index, "location" :availableLocations[index]};
            }
		    
		]]>
	</code>
</script>

That's all. You now have an API that is accessible to other developers. Let us see next how easy it is to invoke this script through HTTP:

curl "https://varick.apstrata.com/apsdb/rest/O763A7F690/RunScript?apsdb.scriptName=createGame
&apsws.time=1419406233582&apsws.authSig=1933c4b633b2ad05c40c2bd7c7ad0aa8
&apsws.responseType=jsoncdp&apsws.authMode=simple
&type=fruits&level=average"
 
// You can also use another option by replacing "apsdb.scriptName=createGame" with "/r/createGame"
 
curl "https://varick.apstrata.com/apsdb/rest/O763A7F690/r/createGame?
&apsws.time=1419406245563&apsws.authSig=1235c4b633b2ade5c50c2bd7c7ad0bg5
&apsws.responseType=jsoncdp&apsws.authMode=simple
&type=fruits&level=average"
String response = "no response yet";
try {
		
	String authKey = "O763A7F690"; // Replace with your Application key
	String baseURL = "https://sandbox.apstrata.com/apsdb/rest";
	
	// Developers who need to use your APIs have to be known by your Apstrata app user directory
	// In the below, we assume that developer dev1 is generating a signature to authenticate his call to your API
	// using his user name and password 			 
	connection = new UserConnection(baseURL, authKey, "dev1@mail.com", "somePassword"); // We create a user connection using the end user's password
    Client client = new Client(BASE_URL, ACCOUNT_KEY, connection);
	Client.AuthMode mode = Client.AuthMode.SIMPLE;
				 
	// Prepare the parameters to send to the SaveDocument API									
	List<NameValuePair> parameters = new ArrayList<NameValuePair>();
	parameters.add(new BasicNameValuePair("apsdb.scriptName","createGame")); 
	parameters.add(new BasicNameValuePair("level","average")); 
	parameters.add(new BasicNameValuePair("type","fruits")); 	
			
	// Invoke the API using the above Client instance 
	// Since we're not uploading files, we send "null" in place of the "files" parameter
	response = client.callAPIJson("RunScript", parameters, null, mode); 
} catch (Exception e) {
	response = "Error: " + e.getMessage();
	e.printStackTrace();
}
Try it!

 Click here to see how to do this using the Apstrata workbench

 

Try it using the Apstrata workbench

Sign in to the Apstrata workbench using your Apstrata application key and secret. Click on "Manage App > Scripts > My Scripts > New". Copy/paste the full code above in the editor page, set the name of the script to "createGame" then click "Save" to save your script.

Once the script is saved, click on "Run". In the parameter form that opens, you can specify parameters to send to your API. Click on the "+" button to create fields and add "level" set to "easy", "average" or "difficult", then add "level" and set its value to one of "fruits" or "animals". Once done, click on "Go" to invoke your API.

Dig deeper

Related tutorials