4
votes

I'm creating an API using Google Cloud Endpoints where I would like to return a "no content" HTTP 204 response if there's nothing to return. I tried returning null, which throws an error on the development server, and a non-empty result on production with status code 200.

It is possible to send out a true 204 empty response or other types or custom responses?

2

2 Answers

5
votes

To return a 204 No Content for a production Python Cloud Endpoints API, you can use VoidMessage.

from google.appengine.ext import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote

class MyMessage(messages.Message):
  ...

@endpoints.api('someapi', 'v1', 'Description')
class MyApi(remote.Service):

  @endpoints.method(MyMessage, message_types.VoidMessage,
                    ...)
  def my_method(self, request):
    ...
    return message_types.VoidMessage()

This currently returns a 200 on the development server, thanks for finding this bug!

0
votes

This probably doesn't help, but the only way I know to manipulate the status code is by raising an exception. There are a default set of exceptions provided which map to 400, 401, 403, 404 and 500. The docs say you can subclass endpoints.ServiceException to generate other status codes, however I haven't been able to get this to work. If you set http_status to anything other than one of those listed above, it always results in a 400.

class TestException(endpoints.ServiceException):
    http_status = httplib.NO_CONTENT

I run a test in my handler like this:

raise TestException('The status should be 204')

And I see this output when testing it using the API explorer:

400 Bad Request

- Show headers -

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "badRequest",
    "message": "The status should be 204"
   }
  ],
  "code": 400,
  "message": "The status should be 204"
 }
}