WorryFree Computers   »   [go: up one dir, main page]

PATCH requests allow you to perform partial updates on many of our REST APIs and in most cases can save bandwidth.

If you have ever tried to do a PATCH request on an App Engine application, you probably realized that it is not possible and that the list of HTTP Methods allowed is whitelisted to the following methods only: GET, POST, HEAD, PUT and DELETE. Trying to perform a PATCH request raises the following Exception:

java.net.ProtocolException: PATCH is not one of the supported http methods: [GET, POST, HEAD, PUT, DELETE]

There is a workaround to this. Most of our APIs support the X-HTTP-Method-Override header. This header can be used in a POST request to “fake” other HTTP methods. Simply set the value of the X-HTTP-Method-Override header to the HTTP method you would like to actually perform.

For example, to make a PATCH request to the Google Tasks API to update only the Notes field of a particular task you could use the following HTTP request:

POST /tasks/v1/lists/@default/tasks/TASK_ID HTTP/1.1
Host: www.googleapis.com
X-HTTP-Method-Override: PATCH
Authorization:  Bearer 
Content-Type:  application/json
Content-Length: 31

{“Notes” : “Patch is working!”}

Which would be equivalent to this HTTP Request, which is not supported on App Engine:

PATCH /tasks/v1/lists/@default/tasks/TASK_ID HTTP/1.1
Host: www.googleapis.com
Authorization:  Bearer 
Content-Type:  application/json
Content-Length: 31

{“Notes” : “Patch is working!”}

For instance, in an App Engine Java environment you could construct and execute this request this way:

URL url = new URL("https://www.googleapis.com/tasks/v1/" +     
    "lists/@default/tasks/" + TASK_ID);
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.addHeader(new HTTPHeader("X-HTTP-Method-Override", "PATCH"));
request.addHeader(new HTTPHeader("Authorization", "Bearer " +
    ACCESS_TOKEN));
request.setPayload("{\"Notes\" : \"Patch is working!\"}".getBytes());

URLFetchService fetchService = URLFetchServiceFactory.getURLFetchService();
HTTPResponse response = fetchService.fetch(request);

This trick can also be used if your application server is behind a firewall, behind a proxy server or in any other environment where HTTP methods other than POST might not be allowed. In that case you could use the X-HTTP-Method-Override header the same way to workaround these limitations.

You may also use our Google APIs Client library for Java or our Google APIs Client library for Python, both of which have support for PATCH requests and use the X-HTTP-Method-Override header when appropriate.


Nicolas Garnier profile | twitter | events

Nicolas joined Google’s Developer Relations in 2008. Since then he's worked on commerce oriented products such as Google Checkout and Google Base. Currently, he is working on Google Apps with a focus on the Google Calendar API, the Google Contacts API, and the Tasks API. Before joining Google, Nicolas worked at Airbus and at the French Space Agency where he built web applications for scientific researchers.

One of the big focuses of this blog (and the team behind it) has been providing compelling examples of how integration with Google Apps APIs can make a product richer and more engaging. As a part of this effort, earlier today we announced Au-to-do, a sample application built using Google APIs.


Au-to-do is a sample implementation of a ticket tracker, built using a combination of Google App Engine, Google Cloud Storage, and Google Prediction APIs.

In addition to providing a demonstration of the power of building on Google App Engine, Au-to-do also provides an example of improving the user experience by integrating with Google Apps. Users of Au-to-do can automatically have tasks created using the Google Tasks API whenever they are assigned a ticket. These tasks have a deep link back to the ticket in Au-to-do. This helps users maintain a single todo list, using a tool that’s already part of the Google Apps workflow.


We’re going to continue work on Au-to-do, and provide additional integrations with Google Apps (and other Google APIs) in the following months.

To learn more, read the full announcement or jump right to the getting started guide.


Dan Holevoet   profile

Dan joined the Google Developer Relations team in 2007. When not playing Starcraft, he works on Google Apps, with a focus on the Calendar and Contacts APIs. He's previously worked on iGoogle, OpenSocial, Gmail contextual gadgets, and the Google Apps Marketplace.

Last month, we launched the Google Tasks API, which received a very warm welcome in the developer community. Google Tasks stores tasks that users enter via Gmail, their mobile device, calendar, or iGoogle homepage. The Google Tasks API provides developers with a powerful set of API endpoints for searching, reading, and updating Google Tasks content and metadata.

To help all of you get started using the Google Tasks API, we wrote a new hands-on tutorial: Getting Started with the Tasks API on Google App Engine. In this tutorial, you will learn how to:
  • Create a simple App Engine app using the Google APIs Client Library.
  • Provide Google Tasks users a mechanism to authorize your app to access their tasks.
  • Make authorized requests to the Tasks API.

By the end of the tutorial, you’ll have an App Engine app that creates a stylized list of tasks for a specific user delivered from the Tasks API:

Check out the tutorial and ask any questions you have in the Google Tasks API forum.



Johan Euphrosine profile | twitter | events

Johan joined Google in 2011 as a Developer Programs Engineer based in Zurich. He is currently focusing on App Engine and Google Apps APIs. Before Google, Johan was providing development services as a Freelancer around FLOSS.


Want to weigh in on this topic? Discuss on Buzz

Editor's Note: This article is written by Stuart Keeble and Gwyn Howell who work at Appogee. Appogee is a UK based reseller of Google Apps and has also developed applications such as Domain Management Studio, Docmail Connect, and Bookmarks, which are available in the Google Apps Marketplace.


The days of the paperless office are not yet upon us, with physical mail delivery still popular for many types of communication including marketing information, financial documents and greetings cards. Over 5000 companies in the UK now use CFH Docmail to print, stuff, and deliver their mail, resulting in over 6 million documents being sent every month. By creating Docmail Connect for Google Apps, we at UK Google focused systems integrator, Appogee, have made it simple for Google Apps users to personalize, print and mail their Google documents..

As well as allowing users to send snail mail from the Google Apps menu, we made the code library for Docmail Connect for Google Apps available in project hosting. Other Google Apps Marketplace providers, such as CRM and ERP applications, can now benefit from being able to easily integrate their applications with Docmail services.

The Challenge

In order to implement the solution we needed to take the Docmail web services and create a Python interface to them. To achieve that we needed a simple Python to Web Services layer we could rely on which would allow us to build the bridge between Google App Engine and Docmail’s API, and then we needed to make the bridge work from Google Docs to the CFH Docmail service. The final challenge we faced was achieving a seamless experience for the user which meant focusing on performance each step of the way.

The Solution (in 3 easy steps)

Step 1: Invoke a SOAP Web Service from App Engine using Python

Our development language of choice is Python. To invoke a SOAP web service we chose to use the SUDs library rather than create a web service interface from scratch. We tested it locally and seemed to work fine. When we uploaded it to App Engine with some sample code, we found some errors due to limitations in App Engine for using sockets and accessing the file system. To get around this, we extended the SUDS library so that it didn’t use the sockets module, and instead of using the file system we used the App Engine memcache API. This worked very well and we were able to send and receive soap requests from App Engine via the Docmail API. Developers may be interested in additional details:
  1. The HttpTransport class has a u2open method which uses python’s socket module to set the timeout. This is not allowed on App Engine, and the timeout setting can be set later using App Engines urlfetch module. The timeout line was removed in a new method:
    def u2open_appengine(self, u2request):
    tm = self.options.timeout
    url = self.u2opener()
    # socket.setdefaulttimeout(tm) can't call this on app engine
    if self.u2ver() < 2.6:
    return url.open(u2request)
    else:
    return url.open(u2request, timeout=tm)
    transport.http.HttpTransport.u2open = u2open_appengine
  2. The SUDs library has an extensible cache class. The SUDs library provides various implementations of this, however we wanted to use the App Engine memcache for performance. To do this, we implemented a new class to use memcache, as shown below:
    class MemCache(cache.Cache):
    def __init__(self, duration=3600):
    self.duration = duration
    self.client = memcache.Client()

    def get(self, id):
    return self.client.get(str(id))

    def getf(self, id):
    return self.get(id)

    def put(self, id, object):
    self.client.set(str(id), object, self.duration)

    def putf(self, id, fp):
    self.put(id, fp)

    def purge(self, id):
    self.client.delete(str(id))

    def clear(self):
    self.client.flush_all()
    This was then plugged into the SUDs client class by overriding the __init__ method.

  3. We can now use the modified SUDs client class to make SOAP calls on App Engine! The full source code for this is available in project hosting.

Step 2: Google Docs to Docmail

CFH publish a full API to allow developers to integrate their applications with Docmail, a subset of which needed to be used by Appogee to create the interface for users to create mailings from Google Docs. Not every Docmail function is enabled in the wrapper, but the principles used can easily be extrapolated to any other function, and the key to it is getting a satisfactory link from Google Docs to Docmail.

The Docmail API can accept documents in a variety of formats including doc, docx, PDF and RTF. In order to use the API, we would need to extract Google Docs content in one of these formats. The Google Docs API has support for exporting in doc, RTF and PDF. We experimented with each before settling on RTF, which, although large in file size, did work. However the Google App Engine urlfetch library has a 1MB request limit, so we were not able to send files larger than 1MB. We evaluated a number of workarounds such as cutting the files up into chunks and sending them separately, bouncing the files off another platform but our only option was to simply prevent files larger than 1 MB from being uploaded. To achieve this we used Ajax calls to check (compute) the file size in real time as they are selected and provide appropriate feedback to the user. The file size cut off is a configurable parameter, so if Google increase the limit we can adjust the app without redeploying the code.

Breaking this integration down, we used the Google Docs API together with the Docmail SOAP API, via our modified implementation of the SUDs library as described in step 1.

The Docmail API must be used in a logical order, to coincide with the wizard pages on the Docmail website. We can illustrate these steps in order:
  1. Create an instance of the Docmail client, which is an extension to the SUDs client class. The client contains the methods we need for further communication with the Docmail API:
    docmail_client = client.Client(USERNAME, PASSWORD, SOURCE)
  2. Create / Retrieve a mailing. To create a new mailing, we create an instance of the Mailing class, and pass it into the create_mailing method:
    mailing = client.Mailing(name='test mailing')
    mailing = docmail_client.create_mailing(mailing)
    To retrieve an existing mailing, we need to know the mailing guid:
    mailing = docmail_client.get_mailing('enter-your-mailing-guid')
  3. Upload a template document. Since we are retrieving documents from Google Docs to be used as the template, we need to download it first. We do this using the Google Docs API:
    docs_client = gdata.docs.client.DocsClient()
    # authenticate client using oauth (see google docs documentation for example code)
    We now need to extract the document. There are various formats you can do this in, but we found by experimenting that RTF worked best, despite being the largest in file size.
    file_content = docs_client.GetFileContent(uri=doc_url + '&exportFormat=rtf')
    And finally upload the template file to docmail:
    docmail_client.add_template_file(mailing.guid, file_content)
  4. Upload a Mailing List Spreadsheet. This is similar code to uploading a template:
    docs_client = gdata.docs.client.DocsClient()
    file_content = docs_client.GetFileContent(uri=doc_url + '&exportFormat=csv')
    docmail_client.add_mailing_list_file(mailing.guid, file_content)
  5. Submit the mailing for processing. The mailing needs to be submitted for processing. Once this has been done, a proof is available for download.
    docmail_client.process_mailing(mailing.guid, False, True)
  6. Finally, we approve and pay for the mailing:
    docmail_client.process_mailing(mailing.guid, True, False)

Step 3 - Performance

When creating a system like Docmail Connect for Google Apps, overall acceptability of the system will be driven as much by performance as by functionality, so we paid particular attention to the key components driving this.

We were conscious that some Google Apps users may have a lot of Google documents, so presenting all of them for selection to a user wasn’t an option. Instead, we load 100 at a time (the default), and send them to the browser using XHR calls so it all happens without the user having to do anything and works quite fast - the user can now select from 1000s of documents within a few seconds.

Next we had to address the connection to the Docmail API, where care must be taken to achieve acceptable throughput. Queries to the API had to be minimized and we didn't want the page submits to be slow - the user should be able to go from one page to the next as quickly as possible. To achieve this, we used the App Engine Task Queue. When a user submits a page which requires communication with the Docmail API we fire off a Task Queue to do the work for us, and then simultaneously navigate the user to the next page in the process. This means that the server is working while the user progresses the workflow. This also means handling timeout errors is easier, as the Task Queue can catch the errors and reinstate another task. But it requires some extra planning as some tasks will not complete until others finish, and process checking needs to ensure new tasks only get fired off when the appropriate time has come.

We hope the wrapper, together with the key learnings written up here will encourage others to have a go at wiring their applications to the Docmail delivery services.

Want to weigh in on this topic? Discuss on Buzz

The Google App Engine team today announced the release of a new SDK v.1.3.1. Many Google Apps developers use the App Engine SDK, or may want to know more about it. So, here is a link to the full blog post, and an excerpt below.

Today we announce the release of version 1.3.1 of the App Engine SDK for both Python and Java. While this release contains plenty of new features and fixes, we've concentrated on using our very first SDK release of 2010 to improve the heart of many App Engine applications: the Datastore.

Here are the three major improvements that 1.3.1 has in store for datastore users:
  • Datastore Query Cursors - Cursors allow applications to save and 'bookmark' their progress through a query, so that it can be resumed later. This works great in combination with paging URLs, as well as processing in the Task Queue API, but there are many other uses. Watch for an upcoming blog post that explores Cursors in the near future. They're also really handy in the context of the next change...
  • No more 1000 result limit - That's right: with addition of Cursors and the culmination of many smaller Datastore stability and performance improvements over the last few months, we're now confident enough to remove the maximum result limit altogether. Whether you're doing a fetch, iterating, or using a Cursor, there's no limits on the number of results.
  • Reduced error rate with Automatic Datastore Retries - We've heard a lot of feedback that you don't want to deal with the Datastore's sporadic errors. In response, App Engine now automatically retries all datastore calls (with the exception of transaction commits) when your applications encounters a datastore error caused by being unable to reach Bigtable. Datastore retries automatically builds in what many of you have been doing in your code already, and our tests have shown it drastically reduces the number of errors your application experiences (by up to 3-4x error reduction for puts, 10-30x for gets).
Read the full post here.

Follow @GoogleAppsDev on Twitter.