4

I have an App Engine service, running Python 3.7, that needs to call and get a response from one of my Cloud Functions via the https.oncall trigger.

I thought I could do so with the following:

import logging
from sys import exit

import firebase_admin

import requests

import google.cloud.logging
client = google.cloud.logging.Client()
client.setup_logging()

firebase_admin.initialize_app()

response = requests.post("https://us-central1-myproject.cloudfunctions.net/functionname", data={"foo": "bar"})

if response.status_code != 200:
    exit("Could not call function! :(") # This is happening

logging.info(f"Yay! Here is the result: {response.text}")

# do something else

exit()

However, I'm getting Request has incorrect Content-Type. from Cloud Functions.

I've tried multiple variations on the request syntax such as: data='{"foo": "bar"}' and data=json.dumps({"foo": "bar"}) but all I can get back is either Request has incorrect Content-Type. or Request has incorrect Content-Type. application/x-www-form-urlencoded.

How do I properly attach my dictionary to my request so that the function receives it in the form of application/json as noted in the Cloud Function docs?

I've read other posts that suggest using the json.dumps() function will tell request to use application/json but Cloud Functions wasn't happy about it.

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82
willbattel
  • 1,040
  • 1
  • 10
  • 37

1 Answers1

2

You're not setting the Content-Type for your request. Starting with requests==2.4.2, you can use the json parameter instead to pass a dictionary and automatically set the Content-Type:

requests.post(url, json={"foo": "bar"})
Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82