Apigee – Getting started with Apigee

Apigee is a full lifecycle API management platform that enables API providers to design, secure, deploy, monitor and scale APIs, managing the entire API lifecycle. How easy is it to start using Apigee?

I decided to find out by trying a Proof of Concept where the objective was to configure a simple API using just the management UI Apigee Edge.

In this POC I wanted to explore the following features:

  • API Design
  • OAuth 2.0 authentication
  • Security Rules
  • Interaction with External Services
  • Cache
  • Scaling
  • Maintenance
  • Logging
  • Deploy and Version strategy

To test Apigee I used a sample GET CITY API REST service available on the Google Cloud. This service returns and saves cities and points of interest. The final API will support the following list of requests:

GET /cities
GET /cities/{city_id}
GET /cities/{city_id}/pointsofinterest
GET /cities/{city_id}/pointsofinterest/{point_of_interest_id}
POST /cities/{city_id}/pointsofinterest
GET /cities/{city_id}/pointsofinterest

Target Endpoint:

https://city-info-214013.appspot.com/api/cities

Let’s first define some keywords and explain how Apigee works.

When you first create an account, you are assigned to an organization. Apigee provides you with one or more organizations, also called orgs. Orgs contains developers, developers applications, API products, API proxies and other items needed to configure the team APIs.

API Proxy

Typically an API proxy is a facade for one or more generic  APIs, services or application. With the API proxy, we have more one extra layer between the client and the services, but we also have an additional control layer to manage our services, configure all the policies and rules and we can:

  • verify security tokens
  • collect analytics information
  • serve requests from the cache  
  • perform traffic management

The proxy endpoints follow the restful principles. The HTTP verbs GET, POST, PUT and DELETE are used except for the verb PATCH.

A proxy is responsible for handling requests from the client, execute all the configured policies and forward the request to the back-end server.

The proxy has two kinds of endpoints:

  • Proxy endpoint: includes client-specific policies and it can have three types of flow: a pre-flow, one or more conditional flows, and a post-flow.
  • Target endpoint: includes policies related to a particular back-end server and it can have the same three types of flow (pre-flow, conditional flow, and post-flow) more an extra post-client-flow which executes after the response is sent to the client.

The target endpoint and proxy consist of XML flows or paths. A proxy has a request path which is the path the request takes from the client to the back-end server and has a response path, which is the path the response takes from the target to the client.

 

Policies

A policy is like a module that implements a specific, limited management function. All the policies are written in XML.

Design APIs

From a developer’s and manager’s perspective, the Apigee Edge Spec Editor can be helpful to build the API structure.

Apigee Edge enables to model our APIs by creating OpenAPI Specifications with Spec Editor.

OpenAPISpecification is the Open API Initiative focused on creating, evolving, and promoting a vendor-neutral API description format based on the Swagger. To know more about OpenAPISpecification: https://www.openapis.org/blog

Developers and clients can use the Spec Editor to add new features, create and update a new proxy automatically, create documentation or just consult the API specifications.

One negative point is that we can’t request the Swagger interface to access our APIs through the web browser, but the Apigee team is working to add this feature, and it should appear soon.

My First proxy

In this experiment, I used my API specs to create a new API proxy. I named the IPI CitiesInfo, and all my requests are working without any extra configuration. To add a new proxy through the ApiEdgee you just have to follow this specification:

  1. Open the Develop menu,
  2. Select the API Proxy menu,
  3. Select the button ‘+ Proxy’,
     
  4. At this point, you can choose between six kinds of proxies. To create the simplest proxy that just makes requests to a backend server, select the Reverse Proxy,
  5. To build a proxy using pre-built specs select the button ‘Use OpenApi’ and select the pretended specs,
  6. Fill in the details if they are incomplete or you are not using specs. Existing API is the backend endpoint,
  7. Click Next,
  8. Select which operations you want to use. But you can select more later.
  9. On Authentication menu select ‘Pass through (none)’,
  10. Select Next. Here you can see and enable or disable the virtual hosts that this proxy will bind when deployed,
  11. After you select Next and you have your first proxy deployed to a test environment and a board where you can configure and test your proxy.
  12. Test your proxy using the endpoint that you can find on ‘Deployments’.

Authentication

Edge provides several methods for authentication. I tried the following methods with the CitiesInfo API:

Basic Authentication: Definition of a user and password and sent this information using the Authorization headers. Just add the the ‘Base Authentication’ policy on Proxy Endpoint, PreFlow with the following code:

<?xml version=“1.0” encoding=“UTF-8” standalone=“yes”?>
<BasicAuthentication async=“false” continueOnError=“false” enabled=“true” name=“BA-Encode-Credentials”>
   <DisplayName>BA-Encode-Credentials</DisplayName>
   <Operation>Encode</Operation>
   <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
   <User ref=“private.client_id”/>
   <Password ref=“private.client_secret”/>
   <AssignTo createNew=“true”>request.header.Authorization</AssignTo>
</BasicAuthentication>


API Key -This policy is used in conjunction with API products, developers, and developers apps. To use this kind of authentication I needed to register a developer and an API Product and associate both in an App. The API key and secret is automatically generated. On the API Proxy  add the ‘Verify API Key’ policy on Proxy Endpoint, PreFlow with the following code:

<?xml version=“1.0” encoding=“UTF-8” standalone=“yes”?>
<VerifyAPIKey async=“false” continueOnError=“false” enabled=“true” name=“Verify-API-Key”>
   <DisplayName>Verify API Key</DisplayName>
   <Properties/>
   <APIKey ref=“request.queryparam.apikey”/>
</VerifyAPIKey>

In this implementation, the client should send the key in a query parameter, but it’s not mandatory.

OAuth 2.0

  • Client Credentials Grant Type ( We just need the client Id and secret id)
  • Password Credentials Grant Type ( We need the clientId, secretId and a valid user. We need an identity service to validate the user)

In order to use OAuth 2.0, I need a service to create a valid token.

With Apigee, it is straightforward and fast to create an OAuth service:

  1. Create a new proxy type ‘No Target’,
  2. Define the base path ‘/oauth’
  3. On Authorization board select ‘Pass through’,
  4. On virtual hosts board select just the secure ones (https).
  5. Deploy the proxy
  6. Add a new conditional flow on the proxy endpoint with the path ‘/accesstoken’,
  7. Add to the previews conditional flow a new ‘OAuth 2.0’ police
  8. Go to the Publish menu and then go to the API Products menu.
  9. Select your API Product,
  10. Edit and add your new OAuth proxy.

The OAuth service creates and validates tokens for all the API Product services. To create a new token request the endpoint /oauth/accesstoken with the client_id, secret_id and grant_type:client_credentials on the request body.

The client should request a token and then request the API with the token, and the Client Credentials Grant Type OAuth is working correctly.

The client_id and secret_id is information regarding the API Product.

The implementation of  Password Credentials Grant Type OAuth need an identity service to validate the user and add a new police ‘Service Callout’ on the OAuth service on GetAccessToken condictinal flow, proxy endpoint with the following code:

<?xml version=“1.0” encoding=“UTF-8”?>
<ServiceCallout name=“SC-AuthenticateUser”>
  <DisplayName>SC-AuthenticateUser</DisplayName>
  <Request variable=“authRequest”>
     <Set>
        <FormParams>
           <FormParam name=“username”>{request.formparam.username}</FormParam>
           <FormParam name=“password”>{request.formparam.password}</FormParam>
        </FormParams>
        <Verb>POST</Verb>
     </Set>
  </Request>
  <Response>authenticationResponse</Response>
  <HTTPTargetConnection>
     <URL>https://myIdentityService</URL>
  </HTTPTargetConnection>
</ServiceCallout>


To request a new token add the user and password the request body.

OAuth 2.0 has an additional two grant types,  Authorization Code and Implicit. ApiGee supports both, but I haven’t tested them.

Security

Apigee Edge provides several ways to ensure security, in this POC, I implemented the security configurations mostly adding simple policies.

  • Validate XML and JSON requests payload. Create a ‘JSON Threat Protection’ and add to the conditional flow where it make sense. ‘JSON Threat Protection’ police code:
<?xml version=“1.0” encoding=“UTF-8” standalone=“yes”?>
<JSONThreatProtection async=“false” continueOnError=“false” enabled=“true” name=“JSONThreatProtection”>
   <DisplayName>JSONThreatProtection</DisplayName>
   <Properties/>
   <ArrayElementCount>5</ArrayElementCount>
   <ContainerDepth>2</ContainerDepth>
   <ObjectEntryCount>6</ObjectEntryCount>
   <ObjectEntryNameLength>50</ObjectEntryNameLength>
   <Source>request</Source>
   <StringValueLength>250</StringValueLength>
</JSONThreatProtection>

Regex validates URI, Headers, and payload against regular expressions.

  • Traffic Management:
    • Quota-  Limit the number of requests over a period of time. A police ‘Quota’ with the following code and add to the PreFlow to be included in all the API requests.
<?xml version=“1.0” encoding=“UTF-8” standalone=“yes”?>
<Quota async=“false” continueOnError=“false” enabled=“true” name=“Quota” type=“calendar”>
   <DisplayName>Quota</DisplayName>
   <Properties/>
   <Allow count=“200” countRef=“apiproduct.developer.quota.limit”/>
   <Interval ref=“apiproduct.developer.quota.interval”>1</Interval>
   <TimeUnit ref=“apiproduct.developer.quota.timeunit”>minute</TimeUnit>
   <Distributed>true</Distributed>
   <Synchronous>true</Synchronous>
   <StartTime>2017-02-13 12:00:00</StartTime>
</Quota>

  • Spike Arrest: Protection against traffic spikes. Add a police ‘Quota’ with the following code on the PreFlow to be included in all the API requests.
<?xml version=“1.0” encoding=“UTF-8” standalone=“yes”?>
<SpikeArrest async=“false” continueOnError=“false” enabled=“true” name=“Spike-Arrest”>
   <DisplayName>Spike-Arrest</DisplayName>
   <Properties/>
   <Identifier ref=“client_id”/>
   <Rate ref=“app.spike-arrest”/>
</SpikeArrest>

  • Regular Expression Protection:

Protects against SQL injection attacks. Add a new Regular Expression Protection police to the conditional flows when it makes sense.

<?xml version=“1.0” encoding=“UTF-8” standalone=“yes”?>
<RegularExpressionProtection async=“false” continueOnError=“false” enabled=“true” name=“RegexProtection”>
   <DisplayName>RegexProtection</DisplayName>
   <Source>request</Source>
   <JSONPayload escapeSlashCharacter=“true”>
       <JSONPath>
           <Expression>$.</Expression>
           <Pattern>.*Exception in thread.*</Pattern>
           <Pattern>[\s]*((delete)|(exec)|(drop\s*table)|(insert)|(shutdown)|(update)|(\bor\b))</Pattern>
       </JSONPath>
   </JSONPayload>
</RegularExpressionProtection>

  • TLS between the client and Apigee Edge and between the ApiGee Edge and the backend servers. I didn’t configure TLS but for me is really important that APIGee provides this feature.

Conclusion

To explore Apigee I started with the example available in the documentation, which has all the necessary information to start working with Apigee. It has to be said that enabling authentication and configuring security rules was really easy to set up with Apigee. Also, as a developer it allows me to put more effort into the business logic.

References:

https://docs.apigee.com/

https://www.openapis.org/

Leave a Reply

Your email address will not be published. Required fields are marked *