Skip to content

Add Endpoints 1.1 sample #439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions appengine/standard/endpoints/backend/app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@ threadsafe: true
api_version: 1

handlers:
# The endpoints handler must be mapped to /_ah/spi.
# Apps send requests to /_ah/api, but the endpoints service handles mapping
# those requests to /_ah/spi.
- url: /_ah/spi/.*
# The endpoints handler must be mapped to /_ah/api.
- url: /_ah/api/.*
script: main.api

libraries:
- name: pycrypto
version: 2.6
- name: endpoints
version: 1.0

# Endpoints 1.1 uses background threads for caching and reporting to service
# management and service control.
manual_scaling:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ouch. Is there any plans to make this work with auto-scaled modules?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are, I don't have all the details around it, but once I do I'll be sure to test/update this pull.

Maybe @tbetbetbe can offer some more information.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SG.

instances: 1

beta_settings:
use_endpoints_api_management: true
endpoints_swagger_spec_file: echo-v1_swagger.json

env_variables:
#TODO: The Endpoints service name.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use #TODO, just say "Replace with your endpoints service name, for example your-service.appspot.com"

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

ENDPOINTS_SERVICE_NAME: {your-service.appspot.com}
#TODO: The version Id of the uploaded Endpoints service.
ENDPOINTS_SERVICE_VERSION: {2016-08-01r01}
4 changes: 4 additions & 0 deletions appengine/standard/endpoints/backend/appengine_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from google.appengine.ext import vendor

# Add any libraries installed in the `lib` folder.
vendor.add('lib')
64 changes: 64 additions & 0 deletions appengine/standard/endpoints/backend/echo-v1_swagger.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the flexible endpoints sample, we use yaml for the definition. Is it possible to use yaml here as well or not?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is possible, I think. This swagger is autogenerated from the endpoints service by a new tool. I don't think it has an option to generate yaml, but I can convert it if that's preferred.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's autogenerated don't sweat it.

"basePath": "/_ah/api/echo/v1",
"consumes": [
"application/json"
],
"definitions": {
"MainEcho": {
"properties": {
"message": {
"type": "string"
}
},
"type": "object"
}
},
"info": {
"title": "echo",
"version": "v1"
},
"paths": {
"/echo": {
"post": {
"operationId": "EchoApi_echo",
"parameters": [],
"responses": {
"200": {
"description": "200_response",
"schema": {
"$ref": "#/definitions/MainEcho"
}
}
}
}
},
"/echo/getUserEmail": {
"get": {
"operationId": "EchoApi_getUserEmail",
"parameters": [],
"responses": {
"200": {
"description": "200_response",
"schema": {
"$ref": "#/definitions/MainEcho"
}
}
}
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0",
"securityDefinitions": {
"api_key": {
"in": "query",
"name": "key",
"type": "apiKey"
}
}
}
138 changes: 28 additions & 110 deletions appengine/standard/endpoints/backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,128 +22,46 @@
from protorpc import remote
# [END imports]


# [START messages]
class Greeting(messages.Message):
"""Greeting that stores a message."""
class Echo(messages.Message):
"""An echo that stores a message."""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about A proto Message that contains a simple string field.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

message = messages.StringField(1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about for disambiguation we call this 'content' instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done



class GreetingCollection(messages.Message):
"""Collection of Greetings."""
items = messages.MessageField(Greeting, 1, repeated=True)


STORED_GREETINGS = GreetingCollection(items=[
Greeting(message='hello world!'),
Greeting(message='goodbye world!'),
])
# [END messages]


# [START greeting_api]
@endpoints.api(name='greeting', version='v1')
class GreetingApi(remote.Service):

@endpoints.method(
# This method does not take a request message.
message_types.VoidMessage,
# This method returns a GreetingCollection message.
GreetingCollection,
path='greetings',
http_method='GET',
name='greetings.list')
def list_greetings(self, unused_request):
return STORED_GREETINGS

# ResourceContainers are used to encapsuate a request body and url
# parameters. This one is used to represent the Greeting ID for the
# greeting_get method.
GET_RESOURCE = endpoints.ResourceContainer(
# The request body should be empty.
message_types.VoidMessage,
# Accept one url parameter: and integer named 'id'
id=messages.IntegerField(1, variant=messages.Variant.INT32))

@endpoints.method(
# Use the ResourceContainer defined above to accept an empty body
# but an ID in the query string.
GET_RESOURCE,
# This method returns a Greeting message.
Greeting,
# The path defines the source of the URL parameter 'id'. If not
# specified here, it would need to be in the query string.
path='greetings/{id}',
http_method='GET',
name='greetings.get')
def get_greeting(self, request):
try:
# request.id is used to access the URL parameter.
return STORED_GREETINGS.items[request.id]
except (IndexError, TypeError):
raise endpoints.NotFoundException(
'Greeting {} not found'.format(request.id))
# [END greeting_api]

# [START multiply]
# This ResourceContainer is similar to the one used for get_greeting, but
# this one also contains a request body in the form of a Greeting message.
MULTIPLY_RESOURCE = endpoints.ResourceContainer(
Greeting,
times=messages.IntegerField(2, variant=messages.Variant.INT32,
required=True))
# [START echo_api]
@endpoints.api(name='echo', version='v1')
class EchoApi(remote.Service):

@endpoints.method(
# This method accepts a request body containing a Greeting message
# and a URL parameter specifying how many times to multiply the
# message.
MULTIPLY_RESOURCE,
# This method returns a Greeting message.
Greeting,
path='greetings/multiply/{times}',
# This method takes an Echo message.
Echo,
# This method returns an Echo message.
Echo,
path='echo',
http_method='POST',
name='greetings.multiply')
def multiply_greeting(self, request):
return Greeting(message=request.message * request.times)
# [END multiply]


# [START auth_config]
WEB_CLIENT_ID = 'replace this with your web client application ID'
ANDROID_CLIENT_ID = 'replace this with your Android client ID'
IOS_CLIENT_ID = 'replace this with your iOS client ID'
ANDROID_AUDIENCE = WEB_CLIENT_ID
ALLOWED_CLIENT_IDS = [
WEB_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID,
endpoints.API_EXPLORER_CLIENT_ID]
# [END auth_config]


# [START authed_greeting_api]
@endpoints.api(
name='authed_greeting',
version='v1',
# Only allowed configured Client IDs to access this API.
allowed_client_ids=ALLOWED_CLIENT_IDS,
# Only allow auth tokens with the given audience to access this API.
audiences=[ANDROID_AUDIENCE],
# Require auth tokens to have the following scopes to access this API.
scopes=[endpoints.EMAIL_SCOPE])
class AuthedGreetingApi(remote.Service):
name='echo')
def echo(self, request):
return Echo(message=request.message)

@endpoints.method(
# This method takes an empty request body.
message_types.VoidMessage,
Greeting,
path='greet',
http_method='POST',
name='greet')
def greet(self, request):
# This method returns an Echo message.
Echo,
path='echo/getUserEmail',
http_method='GET',
# Require auth tokens to have the following scopes to access this API.
scopes=[endpoints.EMAIL_SCOPE])
def get_user_email(self, request):
user = endpoints.get_current_user()
user_name = user.email() if user else 'Anonymous'
return Greeting(message='Hello, {}'.format(user_name))
# [END authed_greeting_api]
# If there's no user defined, the request was unauthenticated, so we
# raise 401 Unauthorized.
if not user:
raise endpoints.UnauthorizedException
return Echo(message=user.email())
# [END echo_api]


# [START api_server]
api = endpoints.api_server([GreetingApi, AuthedGreetingApi])
api = endpoints.api_server([EchoApi])
# [END api_server]
57 changes: 29 additions & 28 deletions appengine/standard/endpoints/backend/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,42 +12,43 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import endpoints
import main
import mock
import unittest
from google.appengine.ext import testbed
from protorpc import message_types

class EchoTestCase(unittest.TestCase):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please use pytest style tests. Refer to the test you overwrote here for an example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

"""
Test cases for the Echo API.
"""

def test_list_greetings(testbed):
api = main.GreetingApi()
response = api.list_greetings(message_types.VoidMessage())
assert len(response.items) == 2
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()

def tearDown(self):
self.testbed.deactivate()

def test_get_greeting(testbed):
api = main.GreetingApi()
request = main.GreetingApi.get_greeting.remote.request_type(id=1)
response = api.get_greeting(request)
assert response.message == 'goodbye world!'
def test_echo(self):
api = main.EchoApi()
response = api.echo(main.Echo(
message='Hello world!'))
self.assertEqual('Hello world!', response.message)

def test_get_user_email(self):
api = main.EchoApi()

def test_multiply_greeting(testbed):
api = main.GreetingApi()
request = main.GreetingApi.multiply_greeting.remote.request_type(
times=4,
message='help I\'m trapped in a test case.')
response = api.multiply_greeting(request)
assert response.message == 'help I\'m trapped in a test case.' * 4
with mock.patch('main.endpoints.get_current_user') as user_mock:
user_mock.return_value = None
self.assertRaises(endpoints.UnauthorizedException,
api.get_user_email, message_types.VoidMessage())

user_mock.return_value = mock.Mock()
user_mock.return_value.email.return_value = '[email protected]'
response = api.get_user_email(message_types.VoidMessage())
self.assertEqual('[email protected]', response.message)

def test_authed_greet(testbed):
api = main.AuthedGreetingApi()

with mock.patch('main.endpoints.get_current_user') as user_mock:
user_mock.return_value = None
response = api.greet(message_types.VoidMessage())
assert response.message == 'Hello, Anonymous'

user_mock.return_value = mock.Mock()
user_mock.return_value.email.return_value = '[email protected]'
response = api.greet(message_types.VoidMessage())
assert response.message == 'Hello, [email protected]'
if __name__ == '__main__':
unittest.main()