Lambda function returns constructed key properly, but cant Parse it.

0

When i invoke this Lambda function it seems as if its building this key correctly, but when i try to parse it in android studio using Kotlin, it wont let me parse the key and use it as a value.

Here is the AWS lambda code:

import json import boto3 import os

Create the Bedrock Runtime client.

bedrock_runtime = boto3.client("bedrock-runtime")

def lambda_handler(event, context): model_input = { "taskType": "TEXT_VIDEO", "textToVideoParams": { "text": json.loads(os.environ['NOVAPROMPT']) }, "videoGenerationConfig": { "durationSeconds": 6, "fps": 24, "dimension": "1280x720", "seed": 33, # Change the seed to get a different result }, } try: # Start the asynchronous video generation job. invocation = bedrock_runtime.start_async_invoke( modelId="amazon.nova-reel-v1:1", modelInput=model_input, outputDataConfig={ "s3OutputDataConfig": { "s3Uri": "s3://novabucket" } } )

     # Extract the invocation ID from the invocationArn
    invocation_id = invocation['invocationArn'].split('/')[-1]
    
    # Construct the future object key
    future_object_key = f"{invocation_id}/output.mp4"


    # Return the object key along with other details.
    return {
        "statusCode": 200,
        "body": json.dumps({
            "invocationArn": invocation.get('invocationArn'),
            "requestId": invocation.get('requestId'),
            "futureObjectKey": future_object_key
        })
    }

except Exception as e:
    # Implement error handling here.
    message = e.response["Error"]["Message"]
    return {
        "statusCode": 500,
        "body": json.dumps({"error": message})
    }

Here is part of my Kotlin code in Android Studio:

client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("LambdaInvokeNova", "Failed to hit API: ${e.message}", e) }

                    override fun onResponse(call: Call, response: Response) {

                        Log.d("LambdaInvokeNova", "Received response from API")

                        // Ensure response body is not null
                        val responseBody = response.body?.string()
                        if (responseBody == null) {
                            Log.w("LambdaInvokeNova", "Response body is null")
                            return // Exit if no body
                        }
                        Log.d("LambdaInvokeNova", "Response body: $responseBody") // Log the body


                        if (response.isSuccessful) {
                            Log.d("LambdaInvokeNova", "Success: $responseBody")

                            try {
                                // Parse the JSON response
                                val jsonResponse = JSONObject(responseBody)

                                // Extract the futureObjectKey
                                if (jsonResponse.has("futureObjectKey")) {
                                    val futureObjectKey = jsonResponse.getString("futureObjectKey")
                                    Log.d("LambdaInvokeNova", "futureObjectKey: $futureObjectKey")

                                }else {
                                    Log.w("JSONParsing", "Missing key: futureObjectKey")
                                }
                                // below is letting our video get created
                                try {
                                    Thread.sleep(10000) // Sleep (block) the current thread for 10 seconds
                                } catch (e: InterruptedException) {
                                    e.printStackTrace() // Handle potential interruption
                                }

                                Log.d("LambdaInvokeNova", "Video should be made")
                                Log.d("LambdaInvokeNova", "done sleeping")
                                Log.d("LambdaInvokeNova", "Lets start grabbing the video..")
                            } catch (e: org.json.JSONException) {
                                Log.e("LambdaInvokeNova", "Error parsing JSON: ${e.message}", e)
                            }

                        } else {
                            Log.e("LambdaInvokeNova", "HTTP error: ${response.code} - ${response.message}")
                        }

                        
                        }
                    })
                //invoke functions here!
            }.start()

and here is are some of the logs i get:

2025-05-03 11:53:29.195 23903-27083 LambdaInvokeNova com.example.myroots8 D Success: {"statusCode": 200, "body": "{"invocationArn": "arn:aws:bedrock:us-east-1:145023101762:async-invoke/bynugg5p9jbo", "requestId": null, "futureObjectKey": "bynugg5p9jbo/output.mp4"}"}

2025-05-03 11:53:29.197 23903-27083 JSONParsing com.example.myroots8 W Missing key: futureObjectKey

asked 10 days ago48 views
1 Answer
0
Accepted Answer

Based on the information provided, it appears that the Lambda function is correctly constructing and returning the futureObjectKey, but there's an issue with parsing it in your Android application. Let's analyze the problem and suggest a solution:

  1. The Lambda function is returning a JSON response with a nested structure. The outer JSON object has a "statusCode" and a "body" field. The "body" field contains another JSON string.

  2. In your Kotlin code, you're trying to directly access the "futureObjectKey" from the top-level JSON object, but it's actually nested inside the "body" string.

To fix this, you need to parse the "body" string as a separate JSON object. Here's how you can modify your Kotlin code to correctly extract the futureObjectKey:

try {
    // Parse the JSON response
    val jsonResponse = JSONObject(responseBody)

    // Extract the body string and parse it as JSON
    val bodyString = jsonResponse.getString("body")
    val bodyJson = JSONObject(bodyString)

    // Now extract the futureObjectKey from the body JSON
    if (bodyJson.has("futureObjectKey")) {
        val futureObjectKey = bodyJson.getString("futureObjectKey")
        Log.d("LambdaInvokeNova", "futureObjectKey: $futureObjectKey")
    } else {
        Log.w("JSONParsing", "Missing key: futureObjectKey")
    }

    // Rest of your code...
} catch (e: org.json.JSONException) {
    Log.e("LambdaInvokeNova", "Error parsing JSON: ${e.message}", e)
}

This modification adds an extra step to parse the "body" string as a separate JSON object. Then, it looks for the "futureObjectKey" within this nested JSON object.

By making this change, you should be able to successfully extract and use the futureObjectKey in your Android application. The key is properly constructed by the Lambda function; it just requires an additional parsing step in your Kotlin code due to the nested JSON structure.
Sources
Connecting to an Amazon RDS database in a Lambda function - AWS Lambda
Connecting to an Amazon RDS database in a Lambda function - AWS SDK Code Examples

profile picture
answered 10 days ago
profile pictureAWS
EXPERT
reviewed 9 days ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions