Using an API to Get Predictions
After you deploy a machine learning model on Google Cloud, you can call it from your own application through an API. Below is a simple walkthrough showing how to:
- Set up Google Cloud service account credentials
- Write a Python script to send data to the model
- Create a simple Flask API to return predictions
1. Create a Google Cloud Service Account
First, you need a service account key so your app can access the model.
- Go to APIs & Services → Credentials
- Create a service account key
- Download it as a JSON file
Set this environment variable:
export GOOGLE_APPLICATION_CREDENTIALS="my-service-key.json"
2. Python Client for Sending Data (gcp_client.py)
This script sends data to your deployed model and returns a prediction.
import google.auth
from googleapiclient.discovery import build
credentials, project_id = google.auth.default()
ml = build("ml", "v1", credentials=credentials)
def call_model(features):
model = "deployed_classifier"
version = "v1"
endpoint = f"projects/{project_id}/models/{model}/versions/{version}"
body = {"instances": [{"x": features}]}
resp = ml.projects().predict(name=endpoint, body=body).execute()
return resp.get("predictions", [])
3. Flask App (app.py)
This Flask app exposes a /predict endpoint.
from flask import Flask, request, jsonify
from flask_cors import CORS
from gcp_client import call_model
app = Flask(__name__)
CORS(app)
@app.route("/predict", methods=["POST"])
def predict():
data = request.get_json(force=True)
features = data.get("features")
if features is None:
return jsonify({"error": "Missing features"}), 400
preds = call_model(features)
return jsonify({"prediction": preds[0] if preds else None})
if __name__ == "__main__":
app.run(debug=True)
4. Run the App
Run this:
export FLASK_APP=app.py
flask run
Test with:
curl -X POST http://127.0.0.1:5000/predict \
-H "Content-Type: application/json" \
-d '{"features":[1,2,3,4]}'
Explain Like I'm 10
Imagine a super-smart robot in Google’s cloud. If you send it numbers, it sends back answers.
The service key is your pass that lets your app talk to the robot.
gcp_client.py is like a phone that calls the robot.
app.py is like a receptionist that takes questions and returns answers.