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.
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.404
response.-
400 -
401 -
403 -
404 -
409 -
410 -
412 -
413
404
, except for the following: -
405is returned as501 -
408is returned as503
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

