Google Cloud Endpoints Tips #4 : Understand @API and @APIMethod Annotations

Google Cloud Endpoints provides convenient Annotations in Java to mark which of your classes is the API and which methods are exposed as the API Methods.

It does that via 2 convenient annotations: @API and @APIMethod.

The key points to remember for these annotations are as follows:

  • The @API annotations as per the documentation states “The annotation @Api is used to configure the whole API, and apply to all public methods of a class unless overridden by @APIMethod”. Note the words unless overridden. Often you find that you casually go ahead and mark a class with @API. The result is that all your public methods will be considered as possible candidates for methods of the API.
  • I recommend to use @API and @APIMethod together. Make sure that you mark only those methods that you want to expose as an API method with the @APIMethod annotation. This brings me to the next point that you should be aware of.
  • As per the documentation of @APIMethod, “all public, non static, non bridge methods in a class with an @Api annotation are exposed in the API, whether they have an @ApiMethod annotation or not”. Do make sure to revisit the various methods that you have in your class to avoid exposing them.

The above points are to do with design and it is not that you would not catch them, especially when you test them under the Local API Explorer, but it is important to help understand what goes on behind the scenes and what the tool does when generating the API Discovery Document and the Client Libraries.

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

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

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

Google Cloud Platform Roadshow India – Talks & Experience

March 25, 2014 is a day to remember. A day where Google broke through the ranks with a series of announcements that clearly demonstrated that there was no need to play catch up in the Cloud Platform wars. Instead, how about leapfrogging the competition on multiple fronts?  It did exactly that. Check out the Cloud Platform Live Event.

Google India announced the Cloud Platform Roadshow across 5 Indian metros through April – May 2014. The series kicked off in Hyderabad on April 12 and since then has moved across to Chennai, Bengaluru, Mumbai and is set for Delhi this week.

The day-long event had talks on:

  • Recent Cloud Platform announcements from the March 25 event
  • Pricing Details on the Platform
  • Compute Engine : Overview and Live Demo
  • App Engine : Cloud Endpoints – writing APIs at Google Scale
  • Bridging the gap between PaaS and IaaS : Flexibility + Manageability
  • BigQuery : Query TBs of data in seconds ! Yes you can !
  • Case Studies of actual customer implementations
  • Partner product demos

While I did present at these events, my personal favorites were the Compute Engine and BigQuery sessions, where I learnt a lot. I could not help but hear the wow’s of the audience when they saw what BigQuery can do. Janakiram clearly rocked the audience with his Compute Engine sessions. Googler’s Rohit and Anudeep are all set to make their future talks “must attend” with their ‘jugalbandi’ (fusion or beautiful mix) in presenting technical topics.

If its been a while you have taken a look at the Google Cloud Platform, you owe it to yourself to learn about the various services that are now under a single Cloud Platform umbrella and present a more unified and complete solution.

I was delighted to present the App Engine session during these roadshows and I focused on Google Cloud Endpoints, which provides a service to create RESTful APIs powered by the App Engine platform. If you are looking to scale up your APIs and power it with Google’s infrastructure, Endpoints is the way to go. You can check out my slides.

DSC_2103

The number of queries and feedback from the participants was excellent. Some of the questions are solid enough for me to go back and think more on how it can be addressed. It was very encouraging to learn from some of them that they were excited enough to try things out soon and learn more about the platform.

As of writing, the roadshow makes its last stop at Delhi on May 31. If you live in and around Delhi and want to learn about the Google Cloud Platform, come and spend May 31st to get vowed with multiple product demonstrations. Click that Registration link.

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:

Image

 

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

Google Cloud Endpoints Tutorial – Part 7

Welcome to Part 7 of the Google Cloud Endpoints Tutorial.

The full series:

  • Part 1 : We looked at writing a Google Cloud Endpoints class manually by using the various annotations and Exception classes that are available. We create a Quotes API that provided a JSON + REST based interface to manage Quotes (add, modify, delete and retrieve quotes).
  • Part 2 : We generated the Google Cloud Endpoints class from a JDO Annotated Entity class by using the Code Generation tools provided in the library.
  • Part 3 : Generated the Cloud Endpoints Client Library for Android and wrote an Android application that invokes the Endpoints API.
  • Part 4: We wrote a JavaScript client for our Endpoints API.
  • Part 5: Securing our API
  • Part 6: Calling a Secured API from a JavaScript client.
  • Part 7 : Calling a Secured API from an Android client.

I have also published a 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

In this episode

So far in this series, we looked at writing a Quote API and in the last couple of episodes, we introduced how to secure your API methods so that only authorized clients can invoke the methods and we demonstrated how to make secure calls from our JavaScript client.

In this episode, we shall see how to make secure API calls from our Android client.

What do you need ?

  • You have a working development environment for Google App Engine. This includes the Google Eclipse plugin.
  • The API Project 2 (Quotes Endpoint Project) loaded in your Development Environment. This is the same as the previous episode.
  • You have a working development environment for Android. I have used Eclipse with the ADT Plug-in.
  • Basic understanding of Android Application Development. We will be using the same code that we had used in Part 3 : Writing an Android client.

My Development Environment

  • This remains the same, no changes at all. My development environment is given below:
    • Eclipse Juno
    • Google Eclipse plugin with App Engine SDK 1.8.8
    • Android ADT Plugin with latest Android SDK installed.
    • Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Invoking the Secure API from Android client

In the last post, we had demonstrated how to make a secured call to the insertQuote method from a JavaScript client. In the Android version of that in this episode, we will be using the same code as we have used in Part 3, except that in the Add Quote Activity, we shall be modifying our code to make secured calls from the Android native application.

Let us first revisit the whole thing about Web Client Id and Audiences that we had setup for our Quotes API earlier.

Web Client Id

If you recollect, in the earlier episode, we had visit the Google Cloud Console for our project and create the OAuth Client Id. A screenshot of the Web Client Id is shown below.

Screen Shot 2014-02-14 at 8.45.01 PM

We created a Constants.java file that contained all these IDs as given below:

Notice that the ANDROID_AUDIENCE is what we are going to use here and it has been set to the same value as the WEB_CLIENT_ID.

Additionally, we had updated the @APIMethod for insertQuote and provided the clientIds, that included the Web Client Id and then deployed the API.

Again notice that we have specified the Client Ids that can access the insertQuote method and also mentioned the ANDROID_AUDIENCE in the audiences attribute.

Remember to regenerate your Client Libraries, just in case you have not done so and deploy it as needed. 

Famous Quotes Android Application Code

We are going to use the same code base as the original Famous Quotes Android application that was covered in Part 3I strongly suggest to go through that first to ensure that you have your Android application and all dependencies set up correctly.

If you want to download that source code, it is available here.

Play Services SDK

Since we are going to make an authenticated call from the Android client, the process will be that we will use the currently logged in Google Account on your Android device. Since this requires Account Picker and other classes on Android from the Play Services Library, it is required that you download the correct Play Services SDK and set that up as a library in the application.

Make sure you link up to the correct library depending on the version that you want to target. I tried out my code on a Android 2.3 device too and it bombed with the latest version of the Play Services SDK. As a result of which, I had to link up to a Froyo version of the library.

So, the first thing to do is to ensure that you have the Play Services SDK. For e.g. in the Android SDK Manager, you can see it over here:

cep7-1

Once you install (download) the above packages, they will be available in the ADT Folder\sdk\extras\google folder as given below:

cep7-2

Simply go to your Eclipse environment and Import any of the above projects as applicable. These are Android library projects and make sure you are able to import it successfully. 

Next, simply add the Play Services library project to your Famous Quotes Android application. The Properties page with the library linked up successfully is shown below:

cep7-3

This completes the development environment setup.

Let us look at the parts of the Add Quote Activity that we modified to ensure that the correct credentials are passed over behind the scenes while making the secure calls from the Android client.

AddQuote Activity Source Code

The entire source code for the AddQuote Activity is shown below:

Let us focus on the important parts and how the Account Credentials are setup before invoking the Secure Cloud Endpoints API.

  • Pay attention first to the onCreate(…) method. The code is identical to the earlier one where we setup the onclick listener for the AddQuote button.
  • There is a section starting with the comment //Account Stuff and there we create an instance of the GoogleAccountCredential class. We create that using the usingAudience method. Notice that the Audience Id string has to be created as follows “server:client_id:<AudienceId>
  • Once the GoogleAccountCredential instance is setup, we invoke the setAccountName method. This method uses Android SharedPreferences , to determine if an ACCOUNT_NAME String preference value was set. If yes, we set that account name for the GoogleAccountCredential instance.
  • We check in the next line if the name has been selected, if not – we invoke the chooseAccount() method, that starts the standard Account Picker activity on your Android phone. This will allow you either login or choose from one or more of your accounts on the device. Once selected, we invoke the setAccountName() method again to set the account name in the GoogleAccountCredential instance and set the value in the SharedPreferences too.
  • Now that the the GoogleAccountCredential is all set, the other change you will notice is in the AddQuoteAsyncTask.
  • In the doInBackground method, notice the following line:
    Quoteendpoint.Builder builder = new Quoteendpoint.Builder(
                    AndroidHttp.newCompatibleTransport(),
                    new GsonFactory(),
                    credential);

    Here, we are no longer passing null in the 3rd parameter. We are using the GoogleAccountCredential instance.

AndroidManifest.xml Permissions

We need to add some additional permissions to the AndroidManifest.xml file as given below:

Project Source Code – Download

The source code for the MyAPIProject2 is available in Github. You can download the entire source code over here.

Additionally, the source code for the secure FamousQuotes Android application is also provided over here.

This brings to an end, the series on Cloud Endpoints as I had originally planned out. Hope you liked the series so far. Give me feedback to help me create more and better content.

I do hope to blog about comparing Google Cloud Endpoints with other methods of writing Web Services along with some stuff that I would ideally like the next release of Google Cloud Endpoints to address both in features, samples and documentation.

Google Cloud Endpoints Tutorial – Part 6

Welcome to Part 6 of the Google Cloud Endpoints Tutorial.

The full series:

  • Part 1 : We looked at writing a Google Cloud Endpoints class manually by using the various annotations and Exception classes that are available. We create a Quotes API that provided a JSON + REST based interface to manage Quotes (add, modify, delete and retrieve quotes).
  • Part 2 : We generated the Google Cloud Endpoints class from a JDO Annotated Entity class by using the Code Generation tools provided in the library.
  • Part 3 : Generated the Cloud Endpoints Client Library for Android and wrote an Android application that invokes the Endpoints API.
  • Part 4: We wrote a JavaScript client for our Endpoints API.
  • Part 5: Securing our API
  • Part 6: Calling a Secured API from a JavaScript client.
  • Part 7 : Calling a Secured API from an Android client.

I have also published a 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

In this episode

So far in this series, we looked at writing a Quote API and in the last episode, we introduced how to secure your API methods so that only authorized clients can invoke the methods. We secured the insertQuote method in the last episode and in this episode, we are going to see how to make secure calls from our JavaScript client.

Keep in mind that we had written a JavaScript client for our Endpoints API earlier in Episode 4, so please take a look at that first.

What do you need ?

  • You have a working development environment for Google App Engine. This includes the Google Eclipse plugin.
  • The API Project 2 (Quotes Endpoint Project) loaded in your Development Environment. This is the same as the previous episode, except that we will be focusing on the apitest.html , which is our API client.

My Development Environment

This remains the same, no changes at all. My development environment is given below:

  • Eclipse Juno
  • Google Eclipse plugin with App Engine SDK 1.8.8.
  • Mac + Windows machine (I kept switching from one to another, to keep everyone happy ;-))

Web Client in Action

Let us first try to understand what we are going to create here by seeing the application and security in action.

I am accessing the client at http://mybackendapi.appspot.com/apitest.html. I have currently logged out from all of my Google Accounts.

When I access the above page, I get the following page:

Screen Shot 2014-02-15 at 2.45.24 PM

Notice the Login button shown above. This button is shown if there was no Google Account that was already logged in. If the User was logged in, this button would be invisible and instead we would be having a Welcome message.

Now, we will not yet click on the Login button. Instead we will attempt to insert a new Quote without logging in and verify if the insertQuote method is indeed secured or not. We enter test values in the Author Name and Quote as shown below and click on the Insert Quote button. This will bring up a popup as shown below. In fact this is the response that we have simply displayed and which came from the Endpoints API HTTP Response:

Screen Shot 2014-02-15 at 2.45.46 PM

In the JavaScript code, I log out the response to the console and which you can see below:

Screen Shot 2014-02-15 at 2.45.57 PM

Now, I click on Login and go through the standard OAuth dance, where I choose a Google Account to log in with, give my credentials and then authorize the application. If all is well, I am logged into our client now and we retrieve the User Name from the OAuth API and display a welcome sign on the top, as shown below:

Screen Shot 2014-02-15 at 2.43.57 PM

Now, I can give my sample values for the Author Name and Quote and click on Insert Quote. 

Screen Shot 2014-02-15 at 2.44.37 PM

The record will get inserted and when I do a List Quotes , I will see the new record that I added:Screen Shot 2014-02-15 at 2.44.57 PM

Let us discuss the code now.

Web Client Id

If you recollect, in the earlier episode, we had visit the Google Cloud Console for our project and create the OAuth Client Id. A screenshot of the Web Client Id is shown below.

Screen Shot 2014-02-14 at 8.45.01 PM

Additionally, we had updated the @APIMethod for insertQuote and provided the clientIds, that included the Web Client Id and then deployed the API. 

JavaScript Client

The entire source code for apitest.html is shown below. The code snippets for Login functionality has been borrowed from the sample code provided in the official document by Google.

Let us look at the main points. Parts of the code should be familiar if you have worked with the JavaScript client that was introduced in Part 4 of this series.

  • We have added a Login button to the User Interface.
    <div id=”login”>
    <input id=”loginButton” type=”button” value=”Login”/>
    </div>
  • As covered in an earlier episode, we load the Client API and once the API is loaded, our init method is invoked.
  • In our init method, we are loading two APIs now : the Quote Endpoint API as we have done earlier and the OAuth API.
  • Once both the APIs are successfully loaded, we are invoking the signin method. To the signin method, we are providing two parameters : an immediate mode parameter whose value is set to true and a callback function : handleAuth.
  • In the signin method, we invoke the gapi.auth.authorize method. To that method, we pass the client Id, scope, immediate mode and the callback (handleAuth). Notice that we have initialized the client Id and scope values in the code and they are the same values as the ones we have created via the Google Cloud Console OAuth New Client creation page. These must match for the authentication/authorization to succeed.
  • In the handleAuth method, we get the current User Object. If the User is found with no errors, then we hide the Login button and display the Welcome message. If the User is not found, the Login button is made visible. This is what happens when our page is loaded i.e. Login button is shown or not shown depending on whether the user is logged in or not. This is also known as the immediate mode.
  • Now, if the Login button is shown i.e. authorization still has to be done, then we have a handler for our Login Button as shown below:
    document.getElementById(‘loginButton’).onclick = function() {
             signin(false,handleAuth);
     }
  • If Login Button is clicked, the signin method is called again with the immediate mode set to false and the callback method as the same one i.e. handleAuth. This will invoke the entire Google Login popup and you go through with the Authentication and Authorization cycle.
  • The insertQuote method is slightly modified to display the error in case there is a problem executing the gapi.client.quoteendpoint.insertQuote method.

Project Source Code

The source code for the MyAPIProject2 is available in Github. You can download the entire source code over here.

Hope you liked this episode of the Google Cloud Endpoints tutorial. The next episode will cover making secured API calls from an Android client.