Remote API for Go
The Go SDK includes the
appengine/remote_api
package that lets you
transparently access App Engine services from any Go application. For example,
you can use Remote API to access a production datastore from an app running on
your local machine. You can also use Remote API to access the datastore of one
App Engine app from a different App Engine app.
Enabling Remote API
First, add the
remote_api
url
handler to your
app.yaml
as follows:
- url: /_ah/remote_api
script: _go_app
login: admin
This maps the URL
/_ah/remote_api
to your Go app. Access to this URL is
restricted to administrators for the application.
Then import the
appengine/remote_api
package in one of your project's
packages. Add this line to any of your
.go
source files:
import _ "appengine/remote_api"
During program initialization, the
remote_api
package registers itself as an
endpoint with the
/_ah/remote_api
path. The underscore in the import
declaration means "import this package, but we won't use it directly." (Without
the underscore you would receive an "imported but not used" error message on
compilation.)
Finally, update your app:
goapp deploy <app-directory>
Using the Remote API in a Local Client
The Remote API can be used to write local applications that use App Engine services and access datastore. It is important to note that using the Remote API will incur quota usage on the application you are accessing. Other limitations of the Remote API are discussed in the Remote API article.
Before beginning, make sure the Remote API is enabled in your App Engine
application. The local application can use the Remote API by creating a context
with
remote_api.NewRemoteContext
, and using that in place of the regular App
Engine context in all API calls.
package demo
import (
"net/http"
"time"
"appengine/datastore"
"appengine/remote_api"
)
// GuestbookCount returns the number of guestbook entries from the last week
// stored in the datastore of the app at the given host.
func GuestbookCount(host string, client *http.Client) (int, err) {
c, err := remote_api.NewRemoteContext(host, client)
if err != nil {
return 0, err
}
q := datastore.NewQuery("Greeting").
Filter("Date >=", time.Now().AddDate(0, 0, -7))
return q.Count(c)
}
You need to provide the hostname of your server and a
http.Client
in the call
to
NewRemoteContext
. The provided
http.Client
is responsible for passing
the required authetication information in each request. See the
demos/remote_api
directory within the SDK for a complete example.