8000 Copy Endpoints Python Echo sample to a new location. (#631) · devlance/python-docs-samples@920eb69 · GitHub
[go: up one dir, main page]

Skip to content

Commit 920eb69

Browse files
kdeusJon Wayne Parrott
authored and
Jon Wayne Parrott
committed
Copy Endpoints Python Echo sample to a new location. (GoogleCloudPlatform#631)
1 parent 33942c9 commit 920eb69

File tree

18 files changed

+1136
-0
lines changed

18 files changed

+1136
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
FROM gcr.io/google_appengine/python
2+
3+
RUN apt-get update && \
4+
apt-get install -y python2.7 python-pip && \
5+
apt-get clean && \
6+
rm /var/lib/apt/lists/*_*
7+
8+
ADD . /app
9+
WORKDIR /app
10+
11+
RUN pip install -r requirements.txt
12+
ENTRYPOINT ["gunicorn", "-b", ":8081", "main:app"]

endpoints/getting-started/README.md

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
# Google Cloud Endpoints & Python
2+
3+
This sample demonstrates how to use Google Cloud Endpoints using Python.
4+
5+
For a complete walkthrough showing how to run this sample in different
6+
environments, see the
7+
[Google Cloud Endpoints Quickstarts](https://cloud.google.com/endpoints/docs/quickstarts).
8+
9+
This sample consists of two parts:
10+
11+
1. The backend
12+
2. The clients
13+
14+
## Running locally
15+
16+
### Running the backend
17+
18+
Install all the dependencies:
19+
```bash
20+
$ virtualenv env
21+
$ source env/bin/activate
22+
$ pip install -r requirements.txt
23+
```
24+
25+
Run the application:
26+
```bash
27+
$ python main.py
28+
```
29+
30+
### Using the echo client
31+
32+
With the app running locally, you can execute the simple echo client using:
33+
```bash
34+
$ python clients/echo-client.py http://localhost:8080 APIKEY helloworld
35+
```
36+
37+
The `APIKEY` doesn't matter as the endpoint proxy is not running to do authentication.
38+
39+
## Deploying to Production
40+
41+
See the
42+
[Google Cloud Endpoints Quickstarts](https://cloud.google.com/endpoints/docs/quickstarts).
43+
44+
### Using the echo client
45+
46+
With the project deployed, you'll need to create an API key to access the API.
47+
48+
1. Open the Credentials page of the API Manager in the [Cloud Console](https://console.cloud.google.com/apis/credentials).
49+
2. Click 'Create credentials'.
50+
3. Select 'API Key'.
51+
4. Choose 'Server Key'
52+
53+
With the API key, you can use the echo client to access the API:
54+
```bash
55+
$ python clients/echo-client.py https://YOUR-PROJECT-ID.appspot.com YOUR-API-KEY helloworld
56+
```
57+
58+
### Using the JWT client (with key file)
59+
60+
The JWT client demonstrates how to use a service account to authenticate to endpoints with the service account's private key file. To use the client, you'll need both an API key (as described in the echo client section) and a service account. To create a service account:
61+
62+
1. Open the Credentials page of the API Manager in the [Cloud Console](https://console.cloud.google.com/apis/credentials).
63+
2. Click 'Create credentials'.
64+
3. Select 'Service account key'.
65+
4. In the 'Select service account' dropdown, select 'Create new service account'.
66+
5. Choose 'JSON' for the key type.
67+
68+
To use the service account for authentication:
69+
70+
1. Update the `google_jwt`'s `x-jwks_uri` in `swagger.yaml` with your service account's email address.
71+
2. Redeploy your application.
72+
73+
Now you can use the JWT client to make requests to the API:
74+
```bash
75+
$ python clients/google-jwt-client.py https://YOUR-PROJECT-ID.appspot.com YOUR-API-KEY /path/to/service-account.json
76+
```
77+
78+
### Using the ID Token client (with key file)
79+
80+
The ID Token client demonstrates how to use user credentials to authenticate to endpoints. To use the client, you'll need both an API key (as described in the echo client section) and a OAuth2 client ID. To create a client ID:
81+
82+
1. Open the Credentials page of the API Manager in the [Cloud Console](https://console.cloud.google.com/apis/credentials).
83+
2. Click 'Create credentials'.
84+
3. Select 'OAuth client ID'.
85+
4. Choose 'Other' for the application type.
86+
87+
To use the client ID for authentication:
88+
89+
1. Update the `/auth/info/googleidtoken`'s `audiences` in `swagger.yaml` with your client ID.
90+
2. Redeploy your application.
91+
92+
Now you can use the client ID to make requests to the API:
93+
```bash
94+
$ python clients/google-id-token-client.py https://YOUR-PROJECT-ID.appspot.com YOUR-API-KEY /path/to/client-id.json
95+
```
96+
97+
### Using the App Engine default service account client (no key file needed)
98+
99+
The App Engine default service account client demonstrates how to use the Google App Engine default service account to authenticate to endpoints.
100+
We refer to the project that serves API requests as the server project. You also need to create a client project in the [Cloud Console](https://console.cloud.google.com). The client project is running Google App Engine standard application.
101+
102+
To use the App Engine default service account for authentication:
103+
104+
1. Update the `gae_default_service_account`'s `x-issuer` and `x-jwks_uri` in `swagger.yaml` with your client project ID.
105+
2. Redeploy your server application.
106+
3. Update clients/service_to_service_gae_default/main.py, replace 'YOUR-CLIENT-PROJECT-ID' and 'YOUR-SERVER-PROJECT-ID' with your client project ID and your server project ID.
107+
4. Upload your application to Google App Engine by invoking the following command. Note that you need to provide project ID in the command because there are two projects (server and client projects) here and gcloud needs to know which project to pick.
108+
```bash
109+
$ gcloud app deploy app.yaml --project=YOUR-CLIENT-PROJECT-ID
110+
```
111+
112+
Your client app is now deployed at https://YOUR-CLIENT-PROJECT-ID.appspot.com. When you access https://YOUR-CLIENT-PROJECT-ID.appspot.com, your client calls your server project API using
113+
the client's service account.
114+
115+
### Using the service account client (no key file needed)
116+
117+
The service account client demonstrates how to use a non-default service account to authenticate to endpoints.
118+
We refer to the project that serves API requests as the server project. You also need to create a client project in the [Cloud Console](https://console.cloud.google.com).
119+
The client project is running Google App Engine standard application.
120+
121+
In the example, we use Google Cloud Identity and Access Management (IAM) API to create a JSON Web Token (JWT) for a service account, and use it to call an Endpoints API.
122+
123+
To use the client, you will need to enable "Service Account Actor" role for App Engine default service account:
124+
125+
1. Go to [IAM page](https://console.cloud.google.com/iam-admin/iam) of your client project.
126+
2. For App Engine default service account, from “Role(s)” drop-down menu, select “Project”-“Service Account Actor”, and Save.
127+
128+
You also need to install Google API python library because the client code (main.py) uses googleapiclient,
129+
which is a python library that needs to be uploaded to App Engine with your application code. After you run "pip install -t lib -r requirements",
130+
Google API python client library should have already been installed under 'lib' directory. Additional information can be found
131+
[here](https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#requesting_a_library).
132+
133+
To use the client for authentication:
134+
135+
1. Update the `google_service_account`'s `x-issuer` and `x-jwks_uri` in `swagger.yaml` with your service account email.
136+
2. Redeploy your server application.
137+
3. Update clients/service_to_service_non_default/main.py by replacing 'YOUR-SERVICE-ACCOUNT-EMAIL', 'YOUR-SERVER-PROJECT-ID' and 'YOUR-CLIENT-PROJECT-ID'
138+
with your service account email, your server project ID, and your client project ID, respectively.
139+
4. Upload your application to Google App Engine by invoking the following command. Note that you need to provide project ID in the command because there are two projects (server and client projects) here and gcloud needs to know which project to pick.
140+
```bash
141+
$ gcloud app deploy app.yaml --project=YOUR-CLIENT-PROJECT-ID
142+
```
143+
144+
Your client app is now deployed at https://YOUR-CLIENT-PROJECT-ID.appspot.com. When you access https://YOUR-CLIENT-PROJECT-ID.appspot.com, your client calls your server project API using
145+
the client's service account.
146+
147+
### Using the ID token client (no key file needed)
148+
149+
This example demonstrates how to authenticate to endpoints from Google App Engine default service account using Google ID token.
150+
In the example, we first create a JSON Web Token (JWT) using the App Engine default service account. We then request a Google
151+
ID token using the JWT, and call an Endpoints API using the Google ID token.
152+
153+
We refer to the project that serves API requests as the server project. You also need to create a client project in the [Cloud Console](https://console.cloud.google.com).
154+
The client project is running Google App Engine standard application.
155+
156+
To use the client for authentication:
157+
158+
1. Update the `google_id_token`'s audiences, replace `YOUR-SERVER-PROJECT-ID` with your server project ID.
159+
2. Redeploy your server application.
160+
3. Update clients/service_to_service_google_id_token/main.py, replace 'YOUR-CLIENT-PROJECT-ID' and 'YOUR-SERVER-PROJECT-ID' with your client project ID and your server project ID.
161+
4. Upload your application to Google App Engine by invoking the following command. Note that you need to provide project ID in the command because there are two projects (server and client projects) here and gcloud needs to know which project to pick.
162+
```bash
163+
$ gcloud app deploy app.yaml --project=YOUR-CLIENT-PROJECT-ID
164+
```
165+
166+
Your client app is now deployed at https://YOUR-CLIENT-PROJECT-ID.appspot.com. When you access https://YOUR-CLIENT-PROJECT-ID.appspot.com, your client calls your server project API from
167+
the client's service account using Google ID token.

endpoints/getting-started/app.yaml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
runtime: python
2+
vm: true
3+
entrypoint: gunicorn -b :$PORT main:app
4+
5+
runtime_config:
6+
python_version: 3
7+
8+
beta_settings:
9+
# Enable Google Cloud Endpoints API management.
10+
use_endpoints_api_management: true
11+
# Specify the Swagger API specification.
12+
endpoints_swagger_spec_file: swagger.yaml
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2016 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Example of calling a simple Google Cloud Endpoint API."""
18+
19+
import argparse
20+
21+
import requests
22+
from six.moves import urllib
23+
24+
25+
def make_request(host, api_key, message):
26+
"""Makes a request to the auth info endpoint for Google ID tokens."""
27+
url = urllib.parse.urljoin(host, 'echo')
28+
params = {
29+
'key': api_key
30+
}
31+
body = {
32+
'message': message
33+
}
34+
35+
response = requests.post(url, params=params, json=body)
36+
37+
response.raise_for_status()
38+
return response.text
39+
40+
41+
def main(host, api_key, message):
42+
response = make_request(host, api_key, message)
43+
print(response)
44+
45+
46+
if __name__ == '__main__':
47+
parser = argparse.ArgumentParser(
48+
description=__doc__,
49+
formatter_class=argparse.RawDescriptionHelpFormatter)
50+
parser.add_argument(
51+
'host', help='Your API host, e.g. https://your-project.appspot.com.')
52+
parser.add_argument(
53+
'api_key', help='Your API key.')
54+
parser.add_argument(
55+
'message',
56+
help='Message to echo.')
57+
58+
args = parser.parse_args()
59+
60+
main(args.host, args.api_key, args.message)
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2016 Google Inc. All Rights Reserved.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Example of calling a Google Cloud Endpoint API with an ID token obtained
18+
using the Google OAuth2 flow."""
19+
20+
import argparse
21+
22+
import oauth2client.client
23+
import oauth2client.file
24+
import oauth2client.tools
25+
import requests
26+
from six.moves import urllib
27+
28+
29+
def get_id_token(client_secrets_file, extra_args):
30+
storage = oauth2client.file.Storage('credentials.dat')
31+
credentials = storage.get()
32+
33+
if not credentials or credentials.invalid:
34+
flow = oauth2client.client.flow_from_clientsecrets(
35+
client_secrets_file, scope='email')
36+
credentials = oauth2client.tools.run_flow(
37+
flow, storage, flags=extra_args)
38+
39+
# The ID token is used by Cloud Endpoints, not the access token.
40+
id_token = credentials.token_response['id_token']
41+
42+
return id_token
43+
44+
45+
def make_request(host, api_key, id_token):
46+
"""Makes a request to the auth info endpoint for Google ID tokens."""
47+
url = urllib.parse.urljoin(host, '/auth/info/googleidtoken')
48+
params = {
49+
'key': api_key
50+
}
51+
headers = {
52+
'Authorization': 'Bearer {}'.format(id_token)
53+
}
54+
55+
response = requests.get(url, params=params, headers=headers)
56+
57+
response.raise_for_status()
58+
return response.text
59+
60+
61+
def main(host, api_key, client_secrets_file, extra_args):
62+
id_token = get_id_token(client_secrets_file, extra_args)
63+
response = make_request(host, api_key, id_token)
64+
print(response)
65+
66+
67+
if __name__ == '__main__':
68+
parser = argparse.ArgumentParser(
69+
description=__doc__,
70+
formatter_class=argparse.RawDescriptionHelpFormatter,
71+
parents=[oauth2client.tools.argparser])
72+
parser.add_argument(
73+
'host', help='Your API host, e.g. https://your-project.appspot.com.')
74+
parser.add_argument(
75+
'api_key', help='Your API key.')
76+
parser.add_argument(
77+
'client_secrets_file',
78+
help='The path to your OAuth2 client secrets file.')
79+
80+
args = parser.parse_args()
81+
82+
main(args.host, args.api_key, args.client_secrets_file, args)

0 commit comments

Comments
 (0)
0