http_method='POST', name='t2name', path='t2path', scopes=[]) def getenviron(self, request): return TestResponse(text='%s %d' % (request.name, request.number)) @endpoints.method(message_types.DateTimeMessage, message_types.DateTimeMessage, http_method='POST', name='echodtmsg', path='echo_datetime_message', scopes=[]) def echo_datetime_message(self, request): return request @endpoints.method(TestDateTime, TestDateTime, http_method='POST', name='echodtfield', path='echo_datetime_field', scopes=[]) def echo_datetime_field(self, request): # Make sure we can access the fields of the datetime object. logging.info('Year %d, Month %d', request.datetime_value.year, request.datetime_value.month) return request application = endpoints.api_server([TestService])
#latitude = request.latitude, #longitude = request.longitude, address = request.address, phone = request.phone ) key = store.put() return store.toMessage() # URL: /_ah/api/court-search/v1/places @endpoints.method(message_types.VoidMessage, message_types.VoidMessage, path='places', http_method='OPTIONS') def options_places(self, request): methods = ['GET', 'POST'] #request.response.headers.add_header('Allow', ','.join(methods)) return message_types.VoidMessage() def toMessage(dbPlace): msg = Place( name = dbPlace.name, latitude = dbPlace.location.lat, longitude = dbPlace.location.lon, address = dbPlace.address, phone = dbPlace.phone ) return msg app = endpoints.api_server([CourtSearchApi], restricted=False)
entry = Contact.get_by_id(entity_id) if not entry: message = 'No entity with the id "%s" exists.' % entity_id raise endpoints.NotFoundException(message) return _BuildContactMessage(entry) # TODO implement list message def list(self, request): contact_messages = [] for contact in Contact.query().fetch(): # TODO pack contacts in response def _BuildContactMessage(contact): return ContactMessage(id=contact.key.id(), name=contact.name, email=contact.email) def _BuildContact(message): return Contact(id=message.id, name=message.name, email=message.email) app = endpoints.api_server([ContactApi], restricted=False)
class TestRequest(messages.Message): """Simple ProtoRPC request, for testing.""" name = messages.StringField(1) number = messages.IntegerField(2) class TestResponse(messages.Message): """Simple ProtoRPC response with a text field.""" text = messages.StringField(1) @endpoints.api(name='test_service', version='v1') class TestService(remote.Service): """ProtoRPC test class for Cloud Endpoints.""" @endpoints.method(message_types.VoidMessage, TestResponse, http_method='GET', name='test', path='test', scopes=[]) def test(self, unused_request): return TestResponse(text='Test response') @endpoints.method(TestRequest, TestResponse, http_method='POST', name='t2name', path='t2path', scopes=[]) def getenviron(self, request): return TestResponse(text='%s %d' % (request.name, request.number)) application = endpoints.api_server([TestService])
class Post(EndpointModel): title = ndb.StringProperty(required=True) date = ndb.DateProperty(auto_now_add=True) text = ndb.StringProperty() image = ndb.BlobProperty() owner = ndb.ReferenceProperty(User, collection_name='users') status = ndb.BooleanProperty() class Comments(EndpointModel): text = ndb.StringProperty() post = ndb.ReferenceProperty(Post, collection_name='posts') @endpoints.api(name='aiesecAPI', version='v1', description='API for AIESEC users.') class UserApi(remote.Service): @User.method(user_required=True, request_field=('role', ), path='user', name='user.insert') def insert_user(self, user): user.user = endpoints.get_current_user() user.put() return user application = endpoints.api_server([AiesecApi])
# Insert meme @Meme.method(path='meme/insert', http_method='post', name='meme.insert') def rose_meme_insert(self, a_meme): """Insert a meme in the database. """ # add this object into the database a_meme.put() # return the object that was inserted return a_meme # Read meme @Meme.query_method(path='meme/list', name='meme.list', http_method='GET', query_fields=('limit', 'order', 'pageToken')) def rose_meme_read(self, query): return query # Delete meme @Meme.method(path='meme/delete/{id}', name='meme.delete', http_method='GET', request_fields=('id', )) def rose_meme_delete(self, a_meme): if not a_meme.from_datastore: raise endpoints.NotFoundException('Meme not Found') a_meme.key.delete() return Meme(image_url='Deleted') app = endpoints.api_server([RoseMemeApi], restricted=False)
@my_api.api_class(resource_name='extraname', path='extrapath') class ExtraMethods(remote.Service): """Some extra test methods in the test API.""" @endpoints.method(message_types.VoidMessage, TestResponse, http_method='GET', name='test', path='test', scopes=[]) def test(self, unused_request): return TestResponse(text='Extra test response') @endpoints.api(name='second_service', version='v1') class SecondService(remote.Service): """Second test class for Cloud Endpoints.""" @endpoints.method(message_types.VoidMessage, TestResponse, http_method='GET', name='test_name', path='test', scopes=[]) def second_test(self, unused_request): """Test a second API, same version, same path. Shouldn't collide.""" return TestResponse(text='Second response') application = endpoints.api_server([TestService, ExtraMethods, SecondService])
""" query = Score.query_current_user() if request.order == ScoresListRequest.Order.TEXT: query = query.order(Score.outcome) elif request.order == ScoresListRequest.Order.WHEN: query = query.order(-Score.played) items = [entity.to_message() for entity in query.fetch(request.limit)] return ScoresListResponse(items=items) @endpoints.method(ScoreRequestMessage, ScoreResponseMessage, path='scores', http_method='POST', name='scores.insert') def scores_insert(self, request): """Exposes an API endpoint to insert a score for the current user. Args: request: An instance of ScoreRequestMessage parsed from the API request. Returns: An instance of ScoreResponseMessage containing the score inserted, the time the score was inserted and the ID of the score. """ entity = Score.put_from_message(request) return entity.to_message() APPLICATION = endpoints.api_server([TicTacToeApi], restricted=False)
# ----------------------------- Deletes ----------------------------- @Task.method(user_required=True, request_fields=('id',), path='task/delete/{id}', http_method='GET', name='task.delete') def task_delete(self, a_task): """ Task Delete. """ if not a_task.from_datastore: raise endpoints.NotFoundException("Task not found.") #TODO: Check if current user is in this TaskList # Remove the key from the TaskList parent_task_list = TaskList.get_by_id(a_task.task_list_id) parent_task_list.task_keys.remove(a_task.key) parent_task_list.put() a_task.key.delete() return Task(text="deleted", task_list_id=0) @TaskList.method(user_required=True, request_fields=('id',), path='tasklist/delete/{id}', http_method='GET', name='tasklist.delete') def TaskListDelete(self, a_task_list): """ Delete a TaskList. """ if not a_task_list.from_datastore: raise endpoints.NotFoundException("TaskList not found.") #TODO: Check if current user is in this TaskList # Delete all the tasks for a_task_key in a_task_list.task_keys: a_task_key.delete() # Remove all the references in the TaskUsers TaskList.flush_task_users(a_task_list.id, []) a_task_list.key.delete() return TaskList(title="deleted") APPLICATION = endpoints.api_server([RoseTaskApi], restricted=False)
def DataInsert(self, my_model): logging.error(my_model) my_model.put() return my_model @Data.query_method(query_fields=('name', 'tag'), path='data', name='data.list') def DataList(self, query): return query @Data.method(path='data', http_method='DELETE', name='data.delete') def DataDelete(self, query): logging.error(query) if query.tag: datakey = Data.query(Data.tag == query.tag).get() if query.name: datakey = Data.query(Data.name == query.name).get() logging.error(datakey) if query.tag or query.name: if datakey: logging.error(datakey) datakey.key.delete() return (datakey) application = endpoints.api_server([MyApi], restricted=False)
package = '' class GetGreetingRequest(messages.Message): id = messages.IntegerField(1, variant=messages.Variant.INT32) class HelloGreeting(messages.Message): message = messages.StringField(1) @endpoints.api(name='helloworld', version='v1', description='Cloud Endpoints on non-default Module') class GreetingsApi(remote.Service): @endpoints.method(GetGreetingRequest, HelloGreeting, path='greetings/{id}', http_method='GET', name='greetings.get') def GetGreeting(self, req): return greetings[req.id] greetings = [ HelloGreeting(message='hello world!'), HelloGreeting(message='goodbye world!') ] app = endpoints.api_server([GreetingsApi], restricted=False)
if not a_task.from_datastore: raise endpoints.NotFoundException("Task not found.") #TODO: Check if current user is in this TaskList # Remove the key from the TaskList parent_task_list = TaskList.get_by_id(a_task.task_list_id) parent_task_list.task_keys.remove(a_task.key) parent_task_list.put() a_task.key.delete() return Task(text="deleted", task_list_id=0) @TaskList.method(user_required=True, request_fields=('id', ), path='tasklist/delete/{id}', http_method='GET', name='tasklist.delete') def TaskListDelete(self, a_task_list): """ Delete a TaskList. """ if not a_task_list.from_datastore: raise endpoints.NotFoundException("TaskList not found.") #TODO: Check if current user is in this TaskList # Delete all the tasks for a_task_key in a_task_list.task_keys: a_task_key.delete() # Remove all the references in the TaskUsers TaskList.flush_task_users(a_task_list.id, []) a_task_list.key.delete() return TaskList(title="deleted") APPLICATION = endpoints.api_server([RoseTaskApi], restricted=False)
tt = Timetable(inS, inT) tt.insertItem(x, s) tt.insertItem(y, p) tt.insertItem(z, t) return tt, [kinS, ks, ps, ts], ["1200", "1234", "1235", "1202"] def test(): from gaemodel import timetables from gaemodel import stops modeltt, keys, ids = testCreateTimetable() outString = "" for i in ids: outString += str(stops.getGAEStopByModelId(i)) for k in keys: outString += str(k.get()) gtt = timetables.getGAETimetable(modeltt) gttKey = gtt.put() # outString = None # if gtt != None: # outString = gtt.toTimetable().toXmlString() from gaemodel import transits generictransit = transits.GAETransit() generictransit.ttable = gttKey generictransit.put() return (outString) epapp = endpoints.api_server([StoreWS])
''' Created on May 4, 2013 @author: Baptiste Maingret ''' from google.appengine.ext import endpoints import local_server_api application = endpoints.api_server([local_server_api.LocalServerAPI], restricted=False)
from google.appengine.ext import endpoints from api import EvaluationApi, EntityApi application = endpoints.api_server([EvaluationApi, EntityApi], restricted=False)
description="Test API for storing and accessing information about tv programmes", allowed_client_ids=["519195049393-v60q82ebldojgipslpgnrhpf370gk4cg.apps.googleusercontent.com"]) class ProgrammeAPI(remote.Service): """ Exposes the API resources """ @endpoints.method(Programme, Programme, name="programme.insert", #object received, object returned, name path="programme", #url path component http_method='POST') # actually this is the default def insert_programme(self, request): ProgrammeModel(title=request.title, num_episodes=request.num_episodes).put() return request @endpoints.method(message_types.VoidMessage, ProgrammeList, name="programme.list", path="programmes", http_method='GET') def list_programmes(self, unused_request): programmes = [] for prog in ProgrammeModel.query(): programmes.append(Programme(title=prog.title, num_episodes=prog.num_episodes)) return ProgrammeList(items=programmes) application = endpoints.api_server([ProgrammeAPI])
# entity to be retrieved from it's ID. As in # custom_api_response_messages/main.py, we override the schema of the ProtoRPC # request message to limit to a single field: "id". Since "id" is one of # the helper methods provided by EndpointsModel, we may use it as one of our # request_fields. In general, other than these five, only properties you # define are allowed. @MyModel.method(request_fields=('id',), path='mymodel/{id}', http_method='GET', name='mymodel.get') def MyModelGet(self, my_model): # Since the field "id" is included, when it is set from the ProtoRPC # message, the decorator attempts to retrieve the entity by its ID. If the # entity was retrieved, the boolean from_datastore on the entity will be # True, otherwise it will be False. In this case, if the entity we attempted # to retrieve was not found, we return an HTTP 404 Not Found. # For more details on the behavior of setting "id", see the sample # custom_alias_properties/main.py. if not my_model.from_datastore: raise endpoints.NotFoundException('MyModel not found.') return my_model # This is identical to the example in basic/main.py, however since the # ProtoRPC schema for the model now includes "id", all the values in "items" # will also contain an "id". @MyModel.query_method(path='mymodels', name='mymodel.list') def MyModelList(self, query): return query application = endpoints.api_server([MyApi], restricted=False)
import webapp2 from google.appengine.ext import endpoints from handlers.Recipes import * from handlers.Files import * from service.FoodieService import FoodieService import handlers.Locations as locations locations.register_location_provider(RecipeLocationProvider()) app = webapp2.WSGIApplication([(CreateRecipeHandler.location(), CreateRecipeHandler), (RecipesHandler.location(), RecipesHandler), (IngredientsHandler.location(), IngredientsHandler), (RecipeHandler.location(), RecipeHandler), (DeleteRecipeHandler.location(), DeleteRecipeHandler), (FileUploadHandler.location(), FileUploadHandler), (RemoveFileUploadHandler.location(), RemoveFileUploadHandler)], debug=True) service = endpoints.api_server([FoodieService], restricted=False)
http_method='GET') def removeIngredient(self,request): """ This method will remove an ingrediants. it will find the ingrediant based on user email and ingrediant name and remove it. Returns deleted ingrediant """ qo = ndb.QueryOptions(keys_only=True,limit = 1) qry = Ingredient.query().filter(Ingredient.userEmail==request.userEmail).filter(Ingredient.displayName == request.displayName) toRemove = qry.get() toRemove.key.delete() return toRemove @Ingredient.method(name='ingredients.updateQuantity', path='ingredients/update/{displayName}/{userEmail}/{quantity}', http_method='GET') def updateIngredientQuantity(self,request): """ This method will replace the quantity stored with a new quantity. It will then store the new one and return """ qo = ndb.QueryOptions(keys_only=True,limit = 1) qry = Ingredient.query().filter(Ingredient.userEmail==request.userEmail).filter(Ingredient.displayName == request.displayName) ind = qry.get() ind.quantity = request.quantity ind.put() return ind application = endpoints.api_server([FridgeraiderApi])
#FIXME: should be captured from the Flask request, not built manually server_name = get_raw_server_name() flask_app.config['DEFAULT_SERVER_NAME'] = server_name flask_app.config['CUSTOM_SERVER_NAME'] = server_name #If debug then enable if flask_app.config['DEBUG']: flask_app.debug = True app = DebuggedApplication(flask_app, evalex=True) flask_app.jinja_env.add_extension('jinja2.ext.loopcontrols') flask_app.jinja_env.add_extension('jinja2.ext.autoescape') flask_app.jinja_env.autoescape=True from myApp.filters import has_profile flask_app.jinja_env.filters['has_profile'] = has_profile from google.appengine.ext.appstats import recording app = recording.appstats_wsgi_middleware(flask_app) from google.appengine.ext.deferred import application as deferred_app deferred_app = recording.appstats_wsgi_middleware(deferred_app) from myApp.apis import UserApi, TaskApi api = recording.appstats_wsgi_middleware( endpoints.api_server([UserApi, TaskApi], restricted=False,)) from myApp import admin_views from myApp import views
if not request.owner: raise endpoints.BadRequestException('Missing request field "owner".') expires = '%sZ' % (datetime.utcnow() + timedelta(hours=1)).isoformat()[:19] policy = base64.b64encode(json.dumps({ 'expiration': expires, 'conditions': [ ['eq', '$bucket', GCS_BUCKET], ['eq', '$key', request.filename], ['eq', '$x-goog-meta-owner', request.owner], ], })) signature = base64.b64encode(app_identity.sign_blob(policy)[1]) return StorageSignedUrlResponse( form_action=GCS_API_URL % GCS_BUCKET, bucket=GCS_BUCKET, policy=policy, signature=signature, google_access_id=app_identity.get_service_account_name(), filename=request.filename ) server = endpoints.api_server( [ ImageApi ], restricted=False )
description = messages.StringField(2) class ArtworkCollection(messages.Message): items = messages.MessageField(Artwork, 1, repeated=True) class UploadUrlResponse(messages.Message): url = messages.StringField(1, required=True) class UploadUrlRequest(messages.Message): callback = messages.StringField(1, required=True) @endpoints.api(name='artworks', version='v1', description='API for Artwork management') class ArtworkApi(remote.Service): @endpoints.method(Artwork, Artwork, name='create_artwork', path='create_artworkxxx', http_method='POST') def create_artwork(self, request): return request def list_artwork(self, request): pass @endpoints.method(UploadUrlRequest, UploadUrlResponse, name='fishassholes', path='create/get_upload_url', http_method='POST') def get_upload_url(self, request): upload_url = api.create_upload_url(callback_url=request.callback) return UploadUrlResponse(url=upload_url) application = endpoints.api_server([ArtworkApi])
return StockSymbolList(items=symbols) @endpoints.method(name='addsymbols', path='add', http_method='POST') def addSymbols(self, request): stock = StockSymbols() stock.store() return request @endpoints.method(response_message=StockSymbolCountMessage, name='countsymbols', path='count', http_method='GET') def getSymbolCount(self, request): query = StockSymbol.query() return StockSymbolCountMessage(message=str(query.count())) @endpoints.method(response_message=StockSymbolCountMessage, name='deletesymbols', path='delete', http_method='GET') def deleteSymbols(self, request): symbolkeys = [] for sym in StockSymbol.query(): symbolkeys.append(sym.key) ndb.delete_multi(symbolkeys) message = 'All Symbols Deleted' return StockSymbolCountMessage(message=message) application = endpoints.api_server([SentimentAPI, GetSymbolsAPI])
of TEXT, the results are ordered by the string value of the scores. """ query = Score.query_current_user() if request.order == ScoresListRequest.Order.TEXT: query = query.order(Score.outcome) elif request.order == ScoresListRequest.Order.WHEN: query = query.order(-Score.played) items = [entity.to_message() for entity in query.fetch(request.limit)] return ScoresListResponse(items=items) @endpoints.method(ScoreRequestMessage, ScoreResponseMessage, path='scores', http_method='POST', name='scores.insert') def scores_insert(self, request): """Exposes an API endpoint to insert a score for the current user. Args: request: An instance of ScoreRequestMessage parsed from the API request. Returns: An instance of ScoreResponseMessage containing the score inserted, the time the score was inserted and the ID of the score. """ entity = Score.put_from_message(request) return entity.to_message() APPLICATION = endpoints.api_server([TicTacToeApi], restricted=False)
from google.appengine.ext import ndb, endpoints from protorpc import messages, remote class Task(messages.Message): name = messages.StringField(1, required=True) owner = messages.StringField(2) class TaskList(messages.Message): items = messages.MessageField(Task, 1, repeated=True) @endpoints.api(name='tasks', version='v1', description="Task Api Management") class TaskApi(remote.Service): @endpoints.method(Task, Task, name='task.insert', path='task', http_method='POST') def insert_task(self, request): print request return request application=endpoints.api_server([TaskApi]) #http://localhost:8080/_ah/api/explorer #http://localhost:8080/_ah/api/discovery/v1/apis/tasks/v1/rest #http://localhost:8000/instances
class GuestBookApi(remote.Service): @endpoints.method( MessageMessage, BlankMessage, name='messages.insert', path='guestbook/messages/new', http_method='POST' ) def insert_message(self, request): MESSAGES.append({ 'createdAt': request.createdAt, 'createdBy': request.createdBy, 'content': request.content }) return BlankMessage() @endpoints.method( BlankMessage, MessageListMessage, name='messages.list', path='guestbook/messages', http_method='GET' ) def list_messages(self, request): msgs = [] for msg in MESSAGES: msgs.append(MessageMessage( createdAt=msg['createdAt'], createdBy=msg['createdBy'], content=msg['content'] )) return MessageListMessage(messages=msgs) application = endpoints.api_server([GuestBookApi], restricted=False)
"""Insert a meme in the database. """ # add this object into the database a_meme.put() # return the object that was inserted return a_meme # Read meme @Meme.query_method(path='meme/list', name='meme.list', http_method='GET', query_fields=('limit', 'order', 'pageToken')) def rose_meme_read(self, query): return query # Delete meme @Meme.method(path='meme/delete/{id}', name='meme.delete', http_method='GET', request_fields=('id',)) def rose_meme_delete(self, a_meme): if not a_meme.from_datastore: raise endpoints.NotFoundException('Meme not Found') a_meme.key.delete() return Meme(image_url = 'Deleted') app = endpoints.api_server([RoseMemeApi], restricted=False)
from google.appengine.ext import ndb, endpoints from protorpc import messages, remote class Task(messages.Message): name = messages.StringField(1, required=True) owner = messages.StringField(2) class TaskList(messages.Message): items = messages.MessageField(Task, 1, repeated=True) @endpoints.api(name='tasks', version='v1', description="Task Api Management") class TaskApi(remote.Service): @endpoints.method(Task, Task, name='task.insert', path='task', http_method='POST') def insert_task(self, request): print request return request application = endpoints.api_server([TaskApi]) #http://localhost:8080/_ah/api/explorer #http://localhost:8080/_ah/api/discovery/v1/apis/tasks/v1/rest #http://localhost:8000/instances
@endpoints.api(name='tasks', version='v1', description='A simple task api') class TaskAPI(remote.Service): """This is the main class for the api. The methods defined here that are decorated with the endpoints wrapper will be the endpoint methods.""" @endpoints.method(Task, Task, name='task.insert', path='task', http_method='POST') def insert_task(self, request): TaskModel(name=request.name, owner=request.owner).put() return request @endpoints.method(message_types.VoidMessage, Tasks, name='task.list_tasks', path='tasks', http_method='GET') def list_tasks(self, unused_request): tasks = [] queried_tasks = TaskModel.query() for single_task in queried_tasks: tasks.append(Task(name=single_task.name, owner=single_task.owner)) return Tasks(items=tasks) Application = endpoints.api_server([TaskAPI])
message_types.DateTimeMessage, http_method='POST', name='echodtmsg', path='echo_datetime_message', scopes=[]) def echo_datetime_message(self, request): return request @endpoints.method(TestDateTime, TestDateTime, http_method='POST', name='echodtfield', path='echo_datetime_field', scopes=[]) def echo_datetime_field(self, request): # Make sure we can access the fields of the datetime object. logging.info('Year %d, Month %d', request.datetime_value.year, request.datetime_value.month) return request @my_api.collection(resource_name='extraname', path='extrapath') class ExtraMethods(remote.Service): """Some extra test methods in the test API.""" @endpoints.method(message_types.VoidMessage, TestResponse, http_method='GET', name='test', path='test', scopes=[]) def test(self, unused_request): return TestResponse(text='Extra test response') application = endpoints.api_server([TestService, ExtraMethods])
return WhiskyList(items=items) @endpoints.method(WhiskyRequest, WhiskyDetail, path='whisky/{id}', http_method='GET', name='whisky.get') def whisky_get(self, request): """Query for a given whisky details """ return whiskies[request.id - 1].to_detail() whiskies = [ Whisky(1, "Hart Brothers 18", "Scottish Highlands", "https://www.googleapis.com/freebase/v1/image/m/0291rn1?maxwidth=400", "Royal Brackla"), Whisky(2, "The Glenlivet 12", "Strathspey", "https://www.googleapis.com/freebase/v1/image/m/02cjlm_?maxwidth=400", "The Glenlivet"), Whisky(3, "Bruchladdich 12 (2nd edition)", "Islay", "http://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Mysterious_Bruichladdich12.jpg/391px-Mysterious_Bruichladdich12.jpg", "Bruichladdich"), Whisky(4, "Bowmore Legend", "Islay", "http://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Bowmore_-_Legend.JPG/340px-Bowmore_-_Legend.JPG", "Bowmore") ]; APPLICATION = endpoints.api_server([WhiskyApi], restricted=False)
import os import sys sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib')) from google.appengine.ext import endpoints from todo_app.apis import TodoApi from main import app api = endpoints.api_server([TodoApi], restricted=False)
import os import sys from todo_app.views import MainPage sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib')) from google.appengine.ext import endpoints from todo_app.apis import TodoApi import webapp2 api = endpoints.api_server([TodoApi], restricted=False) app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
path = 'login', name = 'user.login', http_method = 'POST') def singin_user(self,request): current_user = request.email if current_user is None: raise endpoints.UnauthorizedException('No user is logged in.') if (functions.auth_user(current_user)): return (LoginResponse(signedIn = True)) else: raise endpoints.UnauthorizedException('Ivalid token.') @endpoints.method(EmaiRequest,PermissionResponse, path = 'permission', name = 'user.permission', http_method = 'GET') def permission_user(self,request): current_user = request.email if current_user is None: raise endpoints.UnauthorizedException('Invalid token.') if (functions.auth_user(current_user)): return PermissionResponse(permission = functions.permission_user(current_user)) else: raise endpoints.UnauthorizedException('Invalid token.') application = endpoints.api_server([UserApi])
tt.insertItem(y, p) tt.insertItem(z, t) return tt, [kinS, ks, ps, ts], ["1200", "1234", "1235", "1202"] def test(): from gaemodel import timetables from gaemodel import stops modeltt, keys, ids = testCreateTimetable() outString = "" for i in ids: outString += str(stops.getGAEStopByModelId(i)) for k in keys: outString += str(k.get()) gtt = timetables.getGAETimetable(modeltt) gttKey = gtt.put() # outString = None # if gtt != None: # outString = gtt.toTimetable().toXmlString() from gaemodel import transits generictransit = transits.GAETransit() generictransit.ttable = gttKey generictransit.put() return outString epapp = endpoints.api_server([StoreWS])
''' Created on May 23, 2013 @author: Ashish ''' from google.appengine.ext import endpoints from protorpc import messages from protorpc import remote class Sentiment(messages.Message): category = messages.StringField(1) keyword= messages.StringField(2) @endpoints.api(name='sentiment', version='v1', description='Sentiment API') class SentimentAPI(remote.Service): @endpoints.method(request_message=Sentiment,response_message=Sentiment, name='insert', path='add', http_method='POST') def addSentiment(self,request): return request application = endpoints.api_server([SentimentAPI])
#!/usr/bin/python # Copyright (C) 2013 Gerwin Sturm, FoldedSoft e.U. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.ext import endpoints from mirror_api import MirrorApi ApiServer = endpoints.api_server([MirrorApi], restricted=False)
title = messages.StringField(1) completed = messages.BooleanField(2) class TodoList(messages.Message): items = messages.MessageField(Todo, 1, repeated=True) @endpoints.api(name="todos", version="1", description="API for Task Management") class TodoApi(remote.Service): @endpoints.method(Todo, Todo, name="todo.insert", path="todo", http_method="POST") def insert_todo(self, request): todoModel = TodoModel() todoModel.title = request.title if request.completed: todoModel.completed = request.completed else: todoModel.completed = False todoModel.put() return request @endpoints.method(message_types.VoidMessage, TodoList, name="todo.list", path="todos", http_method="GET") def list_todos(self, unused_request): todos = [] for todo in TodoModel.query(): todos.append(Todo(title=todo.title, completed=todo.completed)) return TodoList(items=todos) application = endpoints.api_server([TodoApi])
# The API @endpoints.api(name='sugarchatersion', version='v1', description='Test google endpoints chat') class ChatAPI(remote.Service): # Method to POST a Message @ChatMessage.method( user_required=True, # for OAuth request_fields=('content', ), name='chatMessage.send', path='chatMessage') def send_chatMessage(self, chatMessage): chatMessage.fromUser = endpoints.get_current_user() #from OAuth chatMessage.toChannel = IRC_CHANNEL chatMessage.put() return chatMessage # Method to Get a Conversation @ChatMessage.query_method(user_required=True, query_fields=('limit', 'order', 'pageToken'), name='chatMessage.conversation', path='conversation') def conversation_messages(self, query): return query.filter(ChatMessage.toChannel == IRC_CHANNEL) application = endpoints.api_server([ChatAPI])
change = change_key.get() if change is None: raise endpoints.BadRequestException( 'Invalid change ID.') if request.url_path not in change.upload_paths: raise endpoints.BadRequestException( 'Unexpected upload for path %s.' % request.url_path) if len(request.data) > 900 * 1024: raise endpoints.BadRequestException( 'Uploaded data cannot exceed 900 kilobytes.') publish.create_content( request.change_id, request.url_path, request.content_type, request.data) return GenericResponse() @endpoints.method( CommitRequest, GenericResponse, name='commit', path='commit') def commit(self, request): ValidateUserIsAuthorized() publish.commit_change(request.change_id) return GenericResponse() app = endpoints.api_server([SitePublishApi], restricted=False)
from google.appengine.ext import endpoints import api application = endpoints.api_server([api.Music,], restricted=False)
from google.appengine.ext import endpoints import datetime import pledges import services import webapp2 class CsvHandler(webapp2.RequestHandler): def get(self): filename = str(datetime.datetime.now()) filename = filename.replace(' ', '_').replace(':', '-').split('.')[0] filename = 'pledges-{}.csv'.format(filename) disposition = 'attachment;filename={}'.format(filename) self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = disposition self.response.out.write(pledges.Pledge.to_csv()) all_services = (services.PledgeService(), ) endpoints_application = endpoints.api_server(all_services, restricted=False) routes = (('/public/csv', CsvHandler), ) application = webapp2.WSGIApplication(routes)
class Post(EndpointModel): title = ndb.StringProperty(required=True) date = ndb.DateProperty(auto_now_add=True) text = ndb.StringProperty() image = ndb.BlobProperty() owner = ndb.ReferenceProperty(User,collection_name='users') status = ndb.BooleanProperty() class Comments(EndpointModel): text = ndb.StringProperty() post = ndb.ReferenceProperty(Post,collection_name='posts') @endpoints.api(name='aiesecAPI',version='v1',description='API for AIESEC users.') class UserApi(remote.Service): @User.method(user_required=True, request_field=('role',), path='user', name='user.insert') def insert_user(self, user): user.user = endpoints.get_current_user() user.put() return user application = endpoints.api_server([AiesecApi])
name='user.login', http_method='POST') def singin_user(self, request): current_user = request.email if current_user is None: raise endpoints.UnauthorizedException('No user is logged in.') if (functions.auth_user(current_user)): return (LoginResponse(signedIn=True)) else: raise endpoints.UnauthorizedException('Ivalid token.') @endpoints.method(EmaiRequest, PermissionResponse, path='permission', name='user.permission', http_method='GET') def permission_user(self, request): current_user = request.email if current_user is None: raise endpoints.UnauthorizedException('Invalid token.') if (functions.auth_user(current_user)): return PermissionResponse( permission=functions.permission_user(current_user)) else: raise endpoints.UnauthorizedException('Invalid token.') application = endpoints.api_server([UserApi])
path='/remove', http_method='DELETE') def deleteShortLink(self, request): """ Delete a single short link. Deletes a short link from the datastore. Args: request: the API request for delete Returns: A message containing the result """ sl = ShortLink.query( ShortLink.short_link == request.short_link).fetch(1) if len(sl) == 0: return DeleteShortLinkMessageResponse(status=1, msg='Short link not found') sl[0].key.delete() memcache.delete(request.short_link) deferred.defer(utils.updateMetric, 'delete', os.getenv('HTTP_X_APPENGINE_COUNTRY')) return DeleteShortLinkMessageResponse(short_link=request.short_link, status=0) application = endpoints.api_server([ShortLinkApi])
from backend.greetings import services from google.appengine.ext import endpoints AVAILABLE_SERVICES = [ services.GreetingService, ] app = endpoints.api_server(AVAILABLE_SERVICES, restricted=False)
@endpoints.method(server_proto.GetAllCommentsForPostRequest, server_proto.GetAllCommentsForPostResponse, name='get_all_comments_for_post', path='app.get_all_comments_for_post', http_method='GET') def get_all_comments_for_post(self, request): return self._handler.handle_get_all_comments_for_post(request) @endpoints.method(server_proto.GetAllPopularPostsAtLocationRequest, server_proto.GetAllPopularPostsAtLocationResponse, name='get_all_popular_posts_at_location', path='app.get_all_popular_posts_at_location', http_method='GET') def get_all_popular_posts_at_location(self, request): return self._handler.handle_get_all_popular_posts_at_location(request) @endpoints.method(server_proto.GetPopularLocationsRequest, server_proto.GetPopularLocationsResponse, name='get_popular_locations', path='app.get_popular_locations', http_method='GET') def get_popular_locations(self, request): return self._handler.handle_get_popular_locations(request) @endpoints.method(server_proto.CalculateAllPopularityIndexRequest, server_proto.CalculateAllPopularityIndexResponse, name='calculate_all_popularity_index', path='app.calculate_all_popularity_index', http_method='POST') def calculate_all_popularity_index(self, request): return self._handler.handle_calculate_all_popularity_index(request) endpoints_application = endpoints.api_server([LocationBasedSocialMediaAPI])
from google.appengine.ext import endpoints from api_endpoints.vehicles_api import * from api_endpoints.distances_emissions_api import * from api_endpoints.users_api import * APPLICATION = endpoints.api_server([VehiclesAPI,DistancesEmissionsAPI,UsersAPI], restricted=False)
CourseList, name='get_all_courses_by_college', path='/get_courses', http_method='GET') def get_courses(self, request): """ This is the method that returns the list of the courses :param request: The request object that contains the information about the school :return: List of the courses offered by the given school """ courses = [] for course in tables.SchoolModel.get_by_id(int(request.name)).courses: print course.school.key courses.append( Course(course_id=course.course_id, school=course.school.name, title=course.title)) return CourseList(items=courses) def enroll(self, request): """ This is the method that adds the offered courses to the user's course list :param request: The object that contains the information about the user :return: The course that has been added to the course list """ pass application = endpoints.api_server([ClassApi, user_api.UserApi])
Greeting(message='hello world!'), Greeting(message='goodbye world!'), ]) @endpoints.api(name='CogentSolutionsIPAapi', version='v1') class CogentSolutionsIPAapi(remote.Service): """Helloworld API v1.""" @endpoints.method(message_types.VoidMessage, GreetingCollection, path='hellogreeting', http_method='GET', name='greetings.listGreeting') def greetings_list(self, unused_request): return STORED_GREETINGS ID_RESOURCE = endpoints.api_backend( message_types.VoidMessage, id=messages.IntegerField(1, variant=messages.Variant.INT32)) @endpoints.method(ID_RESOURCE, Greeting, path='hellogreeting/{id}', http_method='GET', name='greetings.getGreeting') def greeting_get(self, request): try: return STORED_GREETINGS.items[request.id] except (IndexError, TypeError): raise endpoints.NotFoundException('Greeting %s not found.' % (request.id,)) application = endpoints.api_server([CogentSolutionsIPAapi], restricted=False)
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google.appengine.ext import endpoints import tictactoe_api application = endpoints.api_server([tictactoe_api.TicTacToeApi], restricted=False)
from google.appengine.ext import endpoints import api application = endpoints.api_server([ api.Music, ], restricted=False)