Reputation: 1
Very new in Google Cloud Platform & hence asking basic question. I am looking for an API which will be hosted in GCP. An External application will call the API to read data from BigQuery. Can anyone help me out with any example Code/Approach?
Looking for an End-to-End cloud based solution based on Python
Upvotes: 0
Views: 1253
Reputation: 6572
You can create a Python
program using the Bigquery
client, then deploy this program as a HTTP
Cloud Function or Cloud Run
service :
from flask import escape
from google.cloud import bigquery
import functions_framework
@functions_framework.http
def your_http_function(request):
#HTTP Cloud Function.
request_json = request.get_json(silent=True)
request_args = request.args
# example to retrieve argument param in the HTTP call
if request_json and 'name' in request_json:
name = request_json['name']
elif request_args and 'name' in request_args:
name = request_args['name']
# Construct a BigQuery client object.
client = bigquery.Client()
query = """
SELECT name, SUM(number) as total_people
FROM `bigquery-public-data.usa_names.usa_1910_2013`
WHERE state = 'TX'
GROUP BY name, state
ORDER BY total_people DESC
LIMIT 20
"""
query_job = client.query(query) # Make an API request.
rows = query_job.result() # Waits for query to finish
for row in rows:
print(row.name)
return rows
You have to deploy your Python
code as a Cloud Function in this example
Your function can be invoked with a HTTP
call with a param name
:
https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME
You can also use Cloud Run
that gives more flexibility because you deploy a Docker
image.
Upvotes: 1
Reputation: 1863
I can't provide you with a complete code example. But:
Do not forget to setup CORS and potential auth, That's it
Upvotes: 1