rubygoogle-api-ruby-client

google-api-ruby-client: Request serialization results in empty requests


replacement_requests = [
  Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: "{{name}}", replace_text: "Joe"),
  Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: "{{age}}", replace_text: "34"),
  Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: "{{address}}", replace_text: "Westwood"),
]

batch_request = Google::Apis::DocsV1::BatchUpdateDocumentRequest.new(requests: replacement_requests)

Given the above code, when I pass this BatcUpdateDocumentRequest instance into my service.batch_update_document function, I receive a 400 bad request. This seems to be related to the way the batch request is being serialized.

To illustrate, if we call batch_request.to_json we receive the following:

"{\"requests\":[{},{},{}]}"

This tells me that something is going wrong during serialization, however my code seems rather canonical.

Any thoughts on why my requests are failing to be serialized?


Solution

  • If my understanding is correct, how about this modification? In your script, the created request body is {"requests":[{},{},{}]}. By this, the error occurs. Please modify the script as follows.

    Modification points:

    By above modification, the request body is created.

    Modified script:

    text1 = Google::Apis::DocsV1::SubstringMatchCriteria.new(text: "{{name}}")
    text2 = Google::Apis::DocsV1::SubstringMatchCriteria.new(text: "{{age}}")
    text3 = Google::Apis::DocsV1::SubstringMatchCriteria.new(text: "{{address}}")
    
    req1 = Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: text1 , replace_text: "Joe")
    req2 = Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: text2, replace_text: "34")
    req3 = Google::Apis::DocsV1::ReplaceAllTextRequest.new(contains_text: text3, replace_text: "Westwood")
    
    replacement_requests = [
        Google::Apis::DocsV1::Request.new(replace_all_text: req1),
        Google::Apis::DocsV1::Request.new(replace_all_text: req2),
        Google::Apis::DocsV1::Request.new(replace_all_text: req3)
    ]
    
    batch_request = Google::Apis::DocsV1::BatchUpdateDocumentRequest.new(requests: replacement_requests)
    
    # result = service.batch_update_document(document_id, batch_request)  # When you request with "batch_request", you can use this.
    

    Request body:

    When above script is run, the following request body is created.

    {"requests":[
      {"replaceAllText":{"containsText":{"text":"{{name}}"},"replaceText":"Joe"}},
      {"replaceAllText":{"containsText":{"text":"{{age}}"},"replaceText":"34"}},
      {"replaceAllText":{"containsText":{"text":"{{address}}"},"replaceText":"Westwood"}}
    ]}
    

    Note:

    References:

    If this didn't work, I apologize.