In many situations, you might want to use common HTTP status codes to indicate
the success or failure of a user's API request. For example, if a user is
attempting to retrieve an entity which doesn't exist, you might want to send an
HTTP 404
status code to say that no entity with the ID entity_id
exists.
You can send such common HTTP status codes by raising an exception provided by the endpoints library as follows:
message = 'No entity with the id "%s" exists.' % entity_id
raise endpoints.NotFoundException(message)
Exceptions provided by Endpoints Frameworks
The endpoints library provides the following exceptions, corresponding to specific HTTP status codes:
Exception | Corresponding HTTP status code |
---|---|
endpoints.BadRequestException |
HTTP 400 |
endpoints.UnauthorizedException |
HTTP 401 |
endpoints.ForbiddenException |
HTTP 403 |
endpoints.NotFoundException |
HTTP 404 |
endpoints.InternalServerErrorException |
HTTP 500 |
Supported HTTP status codes
Cloud Endpoints Frameworks supports a subset of HTTP status codes in API responses. The following table describes the supported codes.
HTTP status codes | Support |
---|---|
HTTP 2xx | HTTP 200 is typically assumed by Endpoints Frameworks if the API method returns successfully.If the API method response type is VoidMessage or the return value of the API method is None , HTTP 204 is set instead. |
HTTP 3xx | HTTP 3xx codes aren't supported. Use of any HTTP 3xx codes results in an HTTP 404 response. |
HTTP 4xx | Only the following HTTP 4xx codes are supported:
404 , except for the following:
|
HTTP 5xx | All HTTP 5xx status codes are converted to HTTP 503 in the client response. |
Creating your own exception classes
If you want to create other exception classes for other HTTP status codes, you
can do so by subclassing endpoints.ServiceException
. The following snippet
shows how to create an exception class that represents an HTTP 409 status code:
import endpoints
import httplib
class ConflictException(endpoints.ServiceException):
"""Conflict exception that is mapped to a 409 response."""
http_status = httplib.CONFLICT