Was this helpful?

This topic covers three examples that illustrate simple JavaScripts that can be executed on the API Platform to customize the behavior of an API. One choice that Apigee provides API developers is whether to solve a particular problem using out-of-the-box policies or using custom JavaScript. Depending on a developer's background, it is usually most convenient to work with a combination of policies and JavaScript applications. For example, you can use policies to address generic requirements such as rate-limiting, mediation, response caching, security and so on, while implementing custom behavior in JavaScript to solve more interesting problems.

The samples are available in the API Platform Samples repository on Github.

Overview

To execute JavaScript on the API Platform:

  1. Write JavaScript to the Apigee JavaScript object model
  2. Create a JavaScript resource under /resources/jsc in your /apiproxy
  3. Create a matching policy of type 'Javascript' /apiproxy/policies
  4. Attach the policy at the appropriate point in the processing flow
  5. Upload, deploy, test and trace API calls in the Management UI to debug your JavaScript

Modifying a response message using JavaScript

Creating a JavaScript resource

This example demonstrates a simple JavaScript app that changes a response message by modifying the HTTP headers and payload of a response generated by the backend service. This JavaScript uses Variables reference, which the API Platform makes available as part of the flow processing. The variables used here are response message variables: response.status, response.headers, and response.content.

JavaScript is included as a 'resource' that is in turn referenced by a policy in a ProxyEndpoint or TargetEndpoint flow.

JavaScript is stored in a directory called /resources/jsc under /apiproxy. JavaScript resources are referenced in policies of type Javascript (note, lower case 's'). The JavaScript resource is identified by a pointer in the ResourceURL element. The name must match exactly.

For example, the following JavaScript can be stored underapiproxy/resources/jsc as a file called changeResponse.js:

response.status ="200";
response.headers['X-Apigee-Test-Header-1'][0]='Test-Header 1 Value 0';
response.headers['X-Apigee-Test-Header-2'][0]='Test-Header 2 Value 0';
response.headers['X-Apigee-Test-Header-2'][1]='Test-Header 2 Value 1';
response.content='This is your code on Apigee!';

Creating a JavaScript policy

JavaScript resources are executed by JavaScript policies. A JavaScript policy references a JavaScript resource by name as ResourceURL. For example, to create a policy that references a JavaScript resource named changeResponse.jsc, the following policy would be created under/apiproxy/policies:

<Javascript name='changeResponse' timeLimit='200'>
    <ResourceURL>jsc://changeResponse.js</ResourceURL>
</Javascript>

Note: The maximum time limit permitted for JavaScript policies to execute in environments in free trial organization is 200 ms.

Attaching JavaScript policies to a ProxyEndpoint

Like other policies, JavaScript policies must be attached to a flow in order to be executed. The attachment point for the policy determines the point in the flow where the JavaScript executes. In the following example, the JavaScript policy is attached to the response pipeline of the ProxyEndpoint PostFlow. The policy will be enforced (that is, the JavaScript will execute) on the ProxyEndpoint response message before it is returned to the client app.

The ProxyEndpoint configuration for a JavaScript policy that modifies the ProxyEndpoint response:

<ProxyEndpoint name="default">
<PostFlow>
    <Response>
      <Step><Name>changeResponse</Name></Step>
    </Response>
  </PostFlow>
  <HTTPProxyConnection>
      <BasePath>/weather</BasePath>
      <VirtualHost>default</VirtualHost>
  </HTTPProxyConnection>
  <RouteRule name="default">
    <TargetEndpoint>default</TargetEndpoint>
  </RouteRule>
</ProxyEndpoint>

Importing and deploying the API proxy

The deploy tool can be used to deploy the API proxy by substituting valid values for username, password, and organization.

$ python tools/deploy.py -n weatherapi -u myname:mypass -o {org_name} -e test -p / -d simpleProxy
Writing simpleProxy/apiproxy/weatherapi.xml to apiproxy/weatherapi.xml
Writing simpleProxy/apiproxy/policies/ChangeResponse.xml to apiproxy/policies/ChangeResponse.xml
Writing simpleProxy/apiproxy/proxies/default.xml to apiproxy/proxies/default.xml
Writing simpleProxy/apiproxy/resources/jsc/changeResponse.jsc to apiproxy/resources/jsc/changeResponse.jsc
Writing simpleProxy/apiproxy/targets/default.xml to apiproxy/targets/default.xml
Imported new proxy version 1
Environment: test
  Revision: 1 BasePath = /
  State: deployed
 

Testing JavaScript

The curl flag -v can be used to view HTTP headers on the response message modified by the JavaScript.

$ curl -v http://{org_name}-test.apigee.net/weather 
< X-Apigee-Test-Header-1: Test-Header 1 Value 0
< X-Apigee-Test-Header-2: Test-Header 2 Value 0
< X-Apigee-Test-Header-2: Test-Header 2 Value 1
< Content-Length: 27

This is your code on Apigee!

Generating a JSON Response

The following JavaScript sample generates a static JSON response to a request.

Creating the JavaScript resource

In this example, the JavaScript resource is referenced in a file called generateResponse.js under /apiproxy/resources/jsc with the following contents:

response.content=''; 
response.headers['Content-Type']='application/json'; 
var json = response.content.asJSON;

json.country = 'us';
json.postalcode = '95123'
json.elevation = 'Very High';

Creating a policy that references the JavaScript resource

In this example, the JavaScript resource is referenced in a file called generateResponse.xml under apiproxy/policies with the following contents:

<Javascript name='generateResponse' timeLimit='200'>
    <ResourceURL>jsc://generateResponse.js</ResourceURL>
</Javascript>

Attaching the JavaScript policy to the ProxyEndpoint response pipeline PostFlow

To execute this policy, the ProxyEndpoint, apiproxy/proxies/default.xml, should be configured as follows:

<ProxyEndpoint name="default">
  <PostFlow>
    <Response>
      <Step>
        <Name>generateResponse</Name>
      </Step>
   </Response>
</PostFlow>
    <HTTPProxyConnection>
        <BasePath>/weather</BasePath>
        <VirtualHost>default</VirtualHost>
    </HTTPProxyConnection>
  <RouteRule name="default">
    <TargetEndpoint>default</TargetEndpoint>
  </RouteRule>
</ProxyEndpoint>

Testing the JavaScript

$ curl http://{org_name}-test.apigee.net/weather
{"country":"us","postalcode":"95123","elevation":"1200"}

Post questions to the Apigee Developer Forum.

Back to API Platform Developer Guide.