You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Endpoint将Google Cloud MySQL接入Android Studio项目?

Hey there! I’ve tackled this exact scenario before, so let me walk you through a step-by-step guide to connect your Google Cloud MySQL instance to your Android app using Google Endpoints. The key thing to remember here is that you shouldn’t connect your Android app directly to MySQL—that’s a huge security risk (anyone who decompiles your app would get your database credentials). Google Endpoints acts as a secure middle layer between your app and the database, which is why the support team recommended it. Let’s dive in:


1. Prep Your Google Cloud MySQL Instance

First, make sure your database is set up to be accessible by your backend service (we’ll build this next):

  • Go to your MySQL instance in the Google Cloud Console, head to the Connections tab.
    • If you’re using a serverless backend like Cloud Functions, enable Private IP (recommended for production) or temporarily allow public access (only for testing, restrict to your backend’s IP).
  • Create a dedicated database user with limited permissions (e.g., SELECT, INSERT, UPDATE—avoid giving full admin access) and note down the username, password, database name, and instance IP/hostname.

2. Build a Backend Service (With Google Endpoints)

We’ll use Cloud Functions as our backend (it’s lightweight and easy to set up), then wrap it with Google Endpoints to manage API access.

Step 2.1: Create a Cloud Function

  1. In the Google Cloud Console, navigate to Cloud Functions → Create Function.
  2. Pick a runtime you’re comfortable with (I’ll use Python for this example).
  3. Paste this sample code into the editor (replace your_table_name with your actual table):
    import os
    import pymysql
    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    
    # Pull database credentials from environment variables (never hardcode these!)
    DB_USER = os.environ.get("DB_USER")
    DB_PASS = os.environ.get("DB_PASS")
    DB_NAME = os.environ.get("DB_NAME")
    DB_HOST = os.environ.get("DB_HOST")
    
    def get_db_connection():
        return pymysql.connect(
            host=DB_HOST,
            user=DB_USER,
            password=DB_PASS,
            database=DB_NAME
        )
    
    # API endpoint to fetch data from MySQL
    @app.route("/api/get-data", methods=["GET"])
    def fetch_data():
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM your_table_name")
        rows = cursor.fetchall()
        conn.close()
        return jsonify(rows)
    
    # API endpoint to add data to MySQL
    @app.route("/api/add-data", methods=["POST"])
    def add_data():
        payload = request.get_json()
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO your_table_name (column1, column2) VALUES (%s, %s)",
            (payload["col1"], payload["col2"])
        )
        conn.commit()
        conn.close()
        return jsonify({"status": "success"})
    
    # Cloud Functions entry point
    def entry_point(request):
        return app(request)
    
  4. Under Runtime, build, connections and security settings, add environment variables for DB_USER, DB_PASS, DB_NAME, and DB_HOST (use the credentials you noted earlier).
  5. Deploy the function and save its URL (you’ll need this for Endpoints).

Step 2.2: Configure Google Endpoints

Endpoints will act as a managed gateway for your Cloud Function API:

  1. Create an openapi.yaml file (you can do this in Cloud Shell or your local machine):
    swagger: "2.0"
    info:
      title: "MySQL Backend API"
      description: "Secure API to interact with Google Cloud MySQL"
      version: "1.0.0"
    schemes:
      - https
    paths:
      /api/get-data:
        get:
          summary: "Fetch data from MySQL"
          operationId: "getData"
          responses:
            200:
              description: "Successfully retrieved data"
      /api/add-data:
        post:
          summary: "Add new data to MySQL"
          operationId: "addData"
          parameters:
            - in: body
              name: payload
              required: true
              schema:
                type: object
                properties:
                  col1:
                    type: string
                  col2:
                    type: string
          responses:
            200:
              description: "Data added successfully"
    x-google-backend:
      address: "YOUR_CLOUD_FUNCTION_URL" # Replace with your function's URL
    
  2. Deploy the Endpoints configuration via Cloud Shell:
    gcloud endpoints services deploy openapi.yaml
    
  3. Once deployed, you’ll get an Endpoints API URL (e.g., https://your-project-id.endpoints.your-region.cloud.goog)—this is what your Android app will call.

3. Connect Your Android App to Endpoints

We’ll use Retrofit (a popular Android HTTP client) to call the Endpoints API.

Step 3.1: Add Dependencies

In your app-level build.gradle file, add these lines to the dependencies block:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Step 3.2: Create API Interface & Data Models

// API Interface
interface MyDatabaseApi {
    @GET("/api/get-data")
    fun getData(): Call<List<DataEntry>>

    @POST("/api/add-data")
    fun addData(@Body payload: DataEntry): Call<ApiResponse>
}

// Data Models
data class DataEntry(
    val col1: String,
    val col2: String
)

data class ApiResponse(
    val status: String
)

Step 3.3: Initialize Retrofit & Make Requests

Add this code wherever you need to interact with the database (e.g., a ViewModel or Activity):

// Initialize Retrofit
val retrofit = Retrofit.Builder()
    .baseUrl("https://your-project-id.endpoints.your-region.cloud.goog/") // Replace with your Endpoints URL
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val apiService = retrofit.create(MyDatabaseApi::class.java)

// Example: Fetch data from the database
apiService.getData().enqueue(object : Callback<List<DataEntry>> {
    override fun onResponse(call: Call<List<DataEntry>>, response: Response<List<DataEntry>>) {
        if (response.isSuccessful) {
            val data = response.body()
            // Update your UI with the fetched data
        } else {
            // Handle error (e.g., show toast)
        }
    }

    override fun onFailure(call: Call<List<DataEntry>>, t: Throwable) {
        // Handle network failure
    }
})

// Example: Add new data to the database
val newEntry = DataEntry("Hello", "World")
apiService.addData(newEntry).enqueue(object : Callback<ApiResponse> {
    override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
        if (response.isSuccessful) {
            // Show success message
        }
    }

    override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
        // Handle network failure
    }
})

Step 3.4: Add Internet Permission

Don’t forget to add this line to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />

4. Security & Best Practices

  • Add Authentication: Use Firebase Auth or Google OAuth2 to restrict access to your Endpoints API—only allow logged-in users to make requests.
  • Avoid Public MySQL Access: For production, use VPC peering or Cloud Functions’ VPC Connector to connect to your MySQL instance privately (no public IP needed).
  • Error Handling: Add proper error logging in your backend and Android app to debug issues quickly.
  • Rate Limiting: Configure Endpoints to rate-limit requests and prevent abuse.

内容的提问来源于stack exchange,提问作者Hazel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:43:22