Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using .format() in a dictionary with an API call

I am making an api call and in doing so I have to manually change the endDate in the payload every day. I can not use .format() inside a dictionary. Can anyone help out?

Current payload: where I am changing the endDate manually

payload = "{\"dimensions\":[\"AdsetId\",\"Adset\",\"CampaignId\",\"Campaign\",\"Device\",\"Day\",\"Month\",\"Year\",\"Week\",\"Os\"],\"metrics\":[\"AdvertiserCost\",\"Displays\",\"ClickThroughRate\",\"Cpc\",\"AppInstalls\",\"Clicks\"],\"timezone\":\"UTC\",\"advertiserIds\":\"69957\",\"currency\":\"USD\",\"startDate\":\"2022-01-01T00:00:00.0000000+00:00\",\"***endDate\":\"2022-01-13***T00:00:00.0000000+00:00\",\"format\":\"csv\"}"

Expected payload:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

payload = "{\"dimensions\":[\"AdsetId\",\"Adset\",\"CampaignId\",\"Campaign\",\"Device\",\"Day\",\"Month\",\"Year\",\"Week\",\"Os\"],\"metrics\":[\"AdvertiserCost\",\"Displays\",\"ClickThroughRate\",\"Cpc\",\"AppInstalls\",\"Clicks\"],\"timezone\":\"UTC\",\"advertiserIds\":\"69957\",\"currency\":\"USD\",\"startDate\":\"2022-01-01T00:00:00.0000000+00:00\",\endDate\":\"{}T00:00:00.0000000+00:00\",\"format\":\"csv\"}".format(today)

Here today will be a variable with today’s date

>Solution :

That’s a string, not a dictionary and the .format thing that you want, works. Guessing that this is in fact JSON data, the normal way to do this sort of thing is to build a python dict and serialize it later. Using a python "f-string" makes it simple to call a function in the string format specification itself. datetime.datetime.utcnow() gives the current UTC time. It can be converted to a date and its isoformat method writes the format you want. So,

import datetime as dt
import json

data = {
    "dimensions": ["AdsetId", "Adset", "CampaignId", "Campaign",
        "Device", "Day", "Month", "Year", "Week", "Os"],
    "metrics": ["AdvertiserCost", "Displays", "ClickThroughRate", 
        "Cpc", "AppInstalls", "Clicks"],
    "timezone": "UTC", 
    "advertiserIds": "69957", 
    "currency": "USD", 
    "startDate": "2022-01-01T00:00:00.0000000+00:00", 
    "endDate": f"{dt.datetime.utcnow.date.isoformat()}T00:00:00.0000000+00:00", 
    "format": "csv"}
    
    
payload = json.dumps(data)
print(payload)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading