Search code examples
jsongoogle-cloud-platformhttp-postgoogle-cloud-scheduler

How to add a JSON body on a HTTP POST request made with Cloud Scheduler? Will it add the "Content-Type": "application/json" header?


When you are creating a new cron job in Cloud Scheduler:

enter image description here

What should I add in the body field, in order to pass a parameter value:

What is the specification of that field? Should I write JSON in there?

Let's say I want to pass this JSON object:

{
  "foo": "bar"
}

Is the "Content-Type": "application/json" automatically added?


Solution

  • You can provide the information you consider appropriate in the body field.

    At least in the case of AppEngineAppTarget- probably the behavior will be the same for HttpTarget, as indicated in the documentation when describing the headers field, they indicate that if the job has an body, Cloud Scheduler sets the following headers:

    Content-Type: By default, the Content-Type header is set to "application/octet-stream". The default can be overridden by explictly setting Content-Type to a particular media type when the job is created. For example, Content-Type can be set to "application/json". ...

    AFAIK, it is not possible to provide the Content-Type or any other custom header from the Google Cloud Web console, but you can use the gcloud CLI if you need to. Please, see the relevant documentation. Pay special attention to the OPTIONAL FLAGS section, and within it, to the --headers, --message-body and --message-body-from-file flags. Your command should look something like:

    gcloud scheduler jobs create http job-name \
      --schedule="0 */3 * * *" \
      --uri="http://your.url.com" \
      --http-method=POST \
      --headers="Content-Type: application/json" \
      --message-body="{\"field1\":\"value1\",\"field2\":\"value2\"}}"
    

    Please, see also this related SO questions 1 2, they could be of help.