pythonjsonpython-requestsrequestgoogle-colaboratory

How to make a Post request to an API using Google Colab


I need to make the following POST request using Google Colab:

POST https://http.msging.net/commands HTTP/1.1
Content-Type: application/json 
Authorization: Key YOUR_TOKEN 

{ 
"id": "a456-42665544000-0123e4567-e89b-12d3", 
"to": "postmaster@wa.gw.msging.net", 
"method": "get", 
"uri": "lime://wa.gw.msging.net/accounts/+55115555555" 
}

I have tried:

import requests
import re

YOUR_TOKEN = "mytoken"

data = { 
"id": "a456-42665544000-0123e4567-e89b-12d3", 
"to": "postmaster@wa.gw.msging.net", 
"method": "get", 
"uri": "lime://wa.gw.msging.net/accounts/+55115555555" 
}

headers = {
  "Content-Type": "application/json", 
  "Authorization": YOUR_TOKEN 
}
response = requests.post('https://http.msging.net/commands', headers=headers, data=data)

print(response)

For which I get:

<Response [400]>

I also tried:

import requests
import re

YOUR_TOKEN = "Key cHJvY29ycG9lc3RldGljYWF2YW5jYWRhMTg6cEFBSXFuYTZOR1FFWnpydFltTlo="

data = { 
"id": "a456-42665544000-0123e4567-e89b-12d3", 
"to": "postmaster@wa.gw.msging.net", 
"method": "get", 
"uri": "lime://wa.gw.msging.net/accounts/+55115555555" 
}

headers = {
  "Content-Type": "application/json", 
  "Authorization": YOUR_TOKEN 
}
response = requests.post('https://http.msging.net/commands HTTP/1.1', headers=headers, data=data)

print(response)

For which I get:

<Response [404]>

How do I get this request using Google Colab?

Here is the documentation, it does not provide examples. Just the requests.


Solution

  • You get a 400 Bad Request error, as—although you set the Content-Type header to application/json—you don't actually send JSON-encoded data.

    As per Python requests documentation, when sending JSON data, you need to either use the data parameter and pass a JSON-encoded string and manually set the Content-Type header to application/json. For example:

    payload = {'some': 'data'}
    r = requests.post(url, data=json.dumps(payload), headers={"Content-Type": "application/json"})
    

    or, if you don't want to encode the dict on your own, use the json parameter instead to pass the dictionary object, and Python requests will automatically encode the data for you, as well as set the Content-Type header to application/json. For instance:

    payload = {'some': 'data'}
    r = requests.post(url, json=payload)
    

    You would still need to add your TOKEN key to the Authorization header, as you already do.