julian
julian

Reputation: 41

POST to google apis compute engine gives 400

I am building a small flask app to handle automatic deployment for another project I am working on.

This involves setting a gcloud firewall rule using googleapis.

I have followed the below documentation.

https://cloud.google.com/compute/docs/reference/latest/firewalls/insert

When I make my POST call in the following manner.

    headers = {
    'Authorization': 'Bearer {}'.format(access_token)
 }
     name = unique_identifier + "-rule"
     payload = {
          "kind": "compute#firewall",
          "name": name,
          "sourceRanges": [
            "0.0.0.0/0"
          ],
          "sourceTags": [
            unique_identifier
          ],
          "allowed": [
              {
                "IPProtocol": "tcp",
                "ports": [
                 port_number
                ]
              }
            ]
        }
     data = json.dumps(payload)
     r =   requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}",   data=data, headers=headers)

where port_number and unique_idenifier are strings. access_token is retrieved using a service account I have set. I am confident that the token is good, since I can make a GET call to a protected resource using the token.

I am using python 3.5.

The response to this POST is the following.

{
"error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required field 'resource' not specified"
   }
  ],
  "code": 400,
  "message": "Required field 'resource' not specified"
 }
}

The error message is claiming that I am missing a field, although I have all the required fields that are specified at the link below.

https://cloud.google.com/compute/docs/reference/latest/firewalls/insert#request-body

What exactly am I doing wrong?

Upvotes: 2

Views: 657

Answers (1)

julian
julian

Reputation: 41

Figured it out. I removed.

data = json.dumps(payload)

and changed

 r =   requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}",   data=data, headers=headers)

to

 r =   requests.post("https://www.googleapis.com/compute/v1/projects/apollo-rocket-chat/global/firewalls?key={MY_API_KEY}",   json=data, headers=headers)

Upvotes: 2

Related Questions