An API is a remote procedure call (RPC) service that provides remote
methods accessible to external clients. Each backend API consists of an RPC
service class that subclasses the
ProtoRPC remote.Service class, and
one or more methods. When you define a method, you must also define
for the requests coming into that method and the responses returned by it.
Message class performs a mapping function so the incoming data can be
extracted and supplied to the service method properly, or supplied properly to
the outgoing response.
If a request has path or query string arguments, you use a
class for the mapping, instead of a simple
Finally, you need to decorate the API service class and class methods, and you
need to define
Message classes for the requests and responses.
Creating the API
The following procedure shows how to decorate your code to create an API implemented in a single class. If you have a multi-class API, see Creating an API implemented with multiple classes. See Decorators for detailed information about all the available decorators.
To create an API:
Add the following required imports:
import endpoints from endpoints import message_types from endpoints import messages from endpoints import remote
Define a subclass of
remote.Serviceand decorate it with
@endpoints.api(name='echo', version='v1') class EchoApi(remote.Service):
Notice that your API name and the name of your service class don't need to be the same. The version number applies to the version of the API. The value that you enter becomes part of the path in the URL to your API. For more information on versions, see Handling API versioning.
Determine what data your method expects from the request and what data is returned, and create a
Messageclass for the request body and response body:
class EchoRequest(messages.Message): message = messages.StringField(1) class EchoResponse(messages.Message): """A proto Message that contains a simple string field.""" message = messages.StringField(1) ECHO_RESOURCE = endpoints.ResourceContainer( EchoRequest, n=messages.IntegerField(2, default=1))
Note that if no arguments appear in the request body, such as in a
GETrequest, you can omit the
Messageclass for the request and simply use the value
If your request has path or query string arguments, replace your
Messageclass with an appropriate
For complete information on forming and using
Messageclasses, see the documentation for the Google Protocol RPC response and request
Create the method for your API, and decorate it with
@endpoints.method( # This method takes a ResourceContainer defined above. ECHO_RESOURCE, # This method returns an Echo message. EchoResponse, path='echo', http_method='POST', name='echo') def echo(self, request):
If your request has path or query string data, replace the request message type with an appropriate
Add the code to serve your API, as described in Creating a web server.