APIs

Google Cloud Monitoring API Tutorial

If you have any projects running on Google Cloud Platform, one of the things that you want to do is to understand various metrics like response times, latencies, database statistics and more. Recently Google released Cloud Monitoring API that allows you to get information on various metrics. These metrics are only expected to grow with time and will help you in numerous ways.These include building dashboards, writing custom alerts, understanding your monthly bills and more.

spacer

I covered a short tutorial from a developer perspective on Google Cloud Monitoring API on ProgrammableWeb recently. Here is the link to the article.

 

Comment rominirani

Dive into HP IDOL OnDemand APIs

The future lies in processing data and deriving some value from it. Often, the process is tedious and could involve multiple sources of data, images, videos and more to link together.

spacer

HP IDOL On Demand is a great set of APIs that is made available by the HP Cloud Platform that make things much easier for the developer.

Check out my article at ProgrammableWeb that goes into the details of the HP IDOL OnDemand APIs and code snippets to get started on them today.

Comment rominirani

Google Cloud Endpoints Tips #6 : The @APIResourceProperty Annotation

In this tip, we are going to discuss the @APIResourceProperty annotation, which is a very handy annotation that you could use for your API.

The documentation states “@ApiResourceProperty provides provides more control over how resource properties are exposed in the API. You can use it on a property getter or setter to omit the property from an API resource. You can also use it on the field itself, if the field is private, to expose it in the API. You can also use this annotation to change the name of a property in an API resource.”

I have intentionally highlighted some of the words in bold to make you focus on what this annotation can be used for. The first two points should be clear enough i.e. you can omit any property from appearing in the API response or to expose a private property.

The third one is something that I believe is very valuable and can make a big difference to your API. Changing the name of a property is useful in two specific cases (there might be others, so do chime in with your comments to augment my points!) :

  • Make the API Property more understandable
  • Reduce the length of the API property name to a short form. This is useful if you really care about the number of bytes in the response. For e.g. you might have an API Property name “AddressLine1″ and you might just want it to be “AL1″ and so on.

Let us understand it with an example:


@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Task {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@ApiResourceProperty(name="tid")
Long id;

@Persistent
@ApiResourceProperty(name="desc")
String description;

@Persistent
@ApiResourceProperty(ignored=AnnotationBoolean.TRUE)
String status;

// Getter / Setter methods
}

Note the following :

  • For the id property, we are using the @APIResourceProperty annotation and providing it a name =”tid”. This means that in the response the field label will be provided as tid.
  • For the description property, we are shortening the property name to desc.
  • For the status property, we are making the ignored attribute as TRUE, so that it does not appear in the result.

A sample listTask method invocation yields the following JSON response for the test data that I have in my system:

spacer

Hope this makes things clear. Go ahead and employ @APIResourceProperty !

List of Cloud Endpoints Tips 

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotations
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation
13 Comments rominirani

Google Cloud Endpoints Tips #5 : Using Cursor and Limit parameters

One of the design decisions that you need to take with your API is how much of data to return. This is especially important for the list*() methods in your Endpoints implementation.

For e.g. if your API is dealing with Blog comments, there is a possibility of a few blog posts being popular and having hundreds of comments. The correct approach for the API would be to provide the client application using the API, with mechanisms to control the following two aspects of any list*() call:

  • Specify the number of results per API call. This is similar to results per page.
  • Allow subsequent calls to specify the particular page or location from where to return the next N results of the API.

Google Cloud Endpoints addresses this via the cursor and limit parameters. The limit parameter tells how many results to retrieve and the cursor parameter tells the API, from which point should it retrieve the results.

To better understand this, we will need to work with a simple example. It will also demonstrate to us that Google API Explorer via which we can test our API, makes it easier for us to understand these parameters.

Let us start with an empty App Engine project and create an Entity say Task as shown below:


@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Task {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
Long id;

@Persistent
String description;

@Persistent
String status;

// Getter / Setter methods

}

Now, generate the Cloud Endpoints code for this Task class via the Eclipse plugin (or maven / command line – depending on your preference). The Endpoint class generated with the TaskEndpoint.java class. Simply focus on the listTask signature that is shown below:

 


public CollectionResponse<Task> listTask(
 @Nullable @Named("cursor") String cursorString,
 @Nullable @Named("limit") Integer limit)

You will notice the 2 parameters that we have discussed before i.e. cursor and limit.

Go ahead and start the application. Go to the API Explorer locally via the /_ah/api/explorer url and insert at least 4-5 Task Records.

Now, go to the API Explorer and listTask method. The form is shown below:

spacer

 

If you simply click Execute here without entering any values in the cursor and limit fields, then you will get the result shown below. In my case , I have create 4 Task Records and hence all the 4 records are returned. spacer

Now, let’s say that we want to just retrieve 2 records per request and not more. Simply provide the value in the limit parameter as shown below and click on Execute.

spacer

This will return you just the first two records. It starts from the beginning since we have not provided any value in the cursor i.e. from where we should start. spacer

Notice in the above screen i.e. the API response, that a value nextPageToken is passed. This is the value that you need to use in your subsequent calls to the listTask method, to get the next set of records as per the limit and from which point. So, if we provide that value in the cursor as shown below and click Execute.

spacer

 

We get the next 2 records as shown below:

spacer

 

Remember that the cursor and limit parameters are optional. So if you do not provide these values, the Endpoint generated code takes care of it in the listTask implementation. 

Hope this makes things clear on how you can ask only for partial results per API Request.

List of Cloud Endpoints Tips 

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotations
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation
15 Comments rominirani

Google Cloud Endpoints Tips #3 : Understand Injected Types

Typically, when you design your API and the associated methods, you do spend some time deciding what parameters will be passed for each API Method.

It pays to know about Injected Types, which are parameters that are given a special treatment by the Cloud Endpoints framework. These parameters when defined in the method signature will not need to be passed explicitly while making the call. Instead it will be the Cloud Endpoints framework that will populate it for you. You can then make sure of this inside of your method implementation.

As per the documentation, Cloud Endpoints supports the following 3 injected types:

  • com.google.appengine.api.users.User
  • javax.servlet.http.HttpServletRequest
  • javax.servlet.ServletContext

The first one is used if you secure your API Endpoint. The User object will be passed to you. Always remember to check the user object for Null value and do your own validations as needed.

The next 2 injected types are very useful, especially if you wish to dig into the details of the HTTP Request , Servlet Context and do some investigation yourself. These two parameters come handy if your API method implementation is tightly coupled with the Web Framework. Maybe that is a hint to revisit your API :-)

List of Cloud Endpoints Tips 

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotations
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation
11 Comments rominirani

Google Cloud Endpoints Tips #2 : Throw the Right Exception Classes

One of the hallmarks of a well-written API is to understand what it throws back to the clients when there is an exception.

For e.g. a REST API should make use of the correct HTTP Status Codes in its response. Some of the well-known status codes are 200 (OK) , 404 (Not Found), 500 (Internal Server Error) and so on. It is very important that you implement your Endpoint classes to throw back the correct status codes.

Cloud Endpoints does provide a mechanism for you to throw back Exception classes that will in return use the correct HTTP Status code in the response sent back to the client. As per the documentation, there are several exception classes made available in the com.google.api.server.spi.response package. Some of these exception classes are:

  • NotFoundException (HTTP 404)
  • UnauthorizedException (HTTP 401)

and so on. The usage is simple too. Here is a snippet for throwing a not found exception:

String message ="No entity exists with ID: "+ entityId;throw new NotFoundException(message);

The above would be the correct way to throw an exception. It is easy to make the mistake of throwing some other Java Exception (Persistence Layer), etc. This will result in a crazy response for the client with a trace, etc. So always catch the exceptions being thrown from the layers that Cloud Endpoints interacts with and then instantiate the correct exception.

Note that you can also create your own custom Exception classes that map to some other HTTP Codes. But do look out in the documentation for the status codes that you should not be overriding with your custom exception classes.

 

One of the areas where you will immediately notice the need for the correct exception classes is the default code that is generated for the endpoints from your Entity class. Look at the get and insert methods that it generates and you will find that it throws Entity Exceptions from the Persistence Layer. This is typically not a good idea and it is best to envelope this with the Exception classes that correctly map to the HTTP Codes.

Developers who are writing Client applications against your API and API tools will thank you.

List of Cloud Endpoints Tips 

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotation
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation
13 Comments rominirani

Google Cloud Endpoints Tips #1: Check Endpoint Deployment Status

While deploying Cloud Endpoints to a live appspot.com domain, it is important to know if your endpoints deployed OK or not. The Logs Viewer of App Engine provides a good way for you to determine that.

Do the following:

  1. Deploy your App Engine project containing Cloud Endpoints.
  2. Once deployed successfully, go to the App Engine Administration Console and go to Logs Viewer.
  3. Scroll through the recent logs by time-stamp and you shall see something that looks like this:

spacer

 

I have 5 Endpoints in my project and for each of the endpoints, it will provide a OK message as shown above.

The above quick tip is referenced from the documentation and it also mentions that in case there was a problem deploying the Endpoint, you should see an ERROR instead of OK.

List of Cloud Endpoints Tips 

  1. Check Endpoint Deployment Status
  2. Throw the Right Exception Classes
  3. Understand Injected Types
  4. Understand @API and @APIMethod Annotations
  5. Using Cursor and Limit parameters
  6. The @APIResourceProperty Annotation
11 Comments rominirani