python-3.xgoogle-calendar-apidocument-body

How to insert another item programmatically into body?


I am trying to build a free/busy body request to Google Calendar API via Python 3.8 . However, when I try to insert a new item into the body request, I am getting a bad request and can't use it.

This code is working:

SUBJECTA = '3131313636@resource.calendar.google.com'

SUBJECTB =  '34343334@resource.calendar.google.com'


    body = {
  "timeMin": now,
  "timeMax": nownext,
  "timeZone": 'America/New_York',
  "items": [{'id': SUBJECTA},{"id": SUBJECTB} ]
}

Good Body result:

{'timeMin': '2019-11-05T11:42:21.354803Z', 
'timeMax': '2019-11-05T12:42:21.354823Z', 
'timeZone': 'America/New_York', 
'items': [{'id': '131313636@resource.calendar.google.com'}, 
{'id': '343334@resource.calendar.google.com'}]}

However, While using this code:

items = "{'ID': '1313636@resource.calendar.google.com'},{'ID': '3383137@resource.calendar.google.com'},{'ID': '383733@resource.calendar.google.com'}"

  body = { 
  "timeMin": now,
  "timeMax": nownext,
  "timeZone": 'America/New_York',
  "items":  items 
}

The Body results contain additional quotes at the start and end position, failing the request:

{'timeMin': '2019-11-05T12:04:41.189784Z', 
'timeMax': '2019-11-05T13:04:41.189804Z', 
'timeZone': 'America/New_York', 
'items': ["{'ID': 13131313636@resource.calendar.google.com},{'ID': 
53333383137@resource.calendar.google.com},{'ID': 
831383733@resource.calendar.google.com},{'ID': 
33339373237@resource.calendar.google.com},{'ID': 
393935323035@resource.calendar.google.com}"]} 

What is the proper way to handle it and send the item list in an accurate way?


Solution

  • If my understanding is correct, how about this answer? Please think of this as just one of several answers.

    Sample script:

    import json  # Added
    
    items = "{'ID': '1313636@resource.calendar.google.com'},{'ID': '3383137@resource.calendar.google.com'},{'ID': '383733@resource.calendar.google.com'}"
    
    items = json.loads(("[" + items + "]").replace("\'", "\""))  # Added
    
    body = { 
      "timeMin": now,
      "timeMax": nownext,
      "timeZone": 'America/New_York',
      "items": items
    }
    
    print(body)
    

    Result:

    If now and nownext are the values of "now" and "nownext", respectively, the result is as follows.

    {
      "timeMin": "now",
      "timeMax": "nownext",
      "timeZone": "America/New_York",
      "items": [
        {
          "ID": "1313636@resource.calendar.google.com"
        },
        {
          "ID": "3383137@resource.calendar.google.com"
        },
        {
          "ID": "383733@resource.calendar.google.com"
        }
      ]
    }
    

    Note:

    If I misunderstood your question and this was not the result you want, I apologize.