7

I need to push data to a website through their API and I'm trying to find a way to use F-string to pass the variable in the data list but couldn't find a way.

Here's what I've tried so far:

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)

#trying to pass *tomorrow* value with f-string below

data = f'[{"date": "{tomorrow}", "price": {"amount": 15100}}]'

response = requests.put('https://api.platform.io/calendar/28528204', headers=headers, data=data)

How can I achieve this?

locq
  • 301
  • 1
  • 5
  • 22
  • 1
    `data` can be a dictionary. – BrownieInMotion Nov 10 '20 at 01:25
  • @BrownieInMotion what does that mean? – locq Nov 10 '20 at 01:27
  • 4
    You should use `{{` to denote a literal `{` in f-strings, but @BrownieInMotion is right; you should use the data structure directly: `data = [{"date": tomorrow, "price": {"amount": 15100}}]`. `requests.put` will automatically use that, but if you must convert it to json use `json.dumps(data)`. Don't construct json strings yourself, always use the `json` module. – Selcuk Nov 10 '20 at 01:29

1 Answers1

10

I would personally do something like this:

import json
import datetime

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)

data = [{
    "date": str(tomorrow),
    "price": {
        "amount": 15100
    }
}]

print(json.dumps(data))

Of course, after this, you can do anything you want with json.dumps(data): in your case, send it in a request.

BrownieInMotion
  • 1,162
  • 6
  • 11
  • Thanks a lot teh value is getting pass correctly but I'm getting a 400 error with syntax error now? – locq Nov 10 '20 at 01:40
  • @locq this seems to be specific to the endpoint. Can you give an example of a request that does not give a syntax error? – BrownieInMotion Nov 10 '20 at 01:41
  • The data only works when single quotes are added: `data = '[{"date": "2020-11-12", "price": {"amount": 7700}}]'` – locq Nov 10 '20 at 01:46
  • 1
    @locq can you try it with the string `data = '[{"date": "2020-11-10", "price": {"amount": 15100}}]'`? – BrownieInMotion Nov 10 '20 at 01:49
  • Yes this works but now I need to pass the variable tomorrow in there – locq Nov 10 '20 at 01:52
  • If your request looks something like response = `requests.put('https://api.platform.io/calendar/28528204', headers=headers, data=json.dumps(data))`, that is the exact string that should be sent. Did you perhaps forget `json.dumps()`? – BrownieInMotion Nov 10 '20 at 01:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/224346/discussion-between-brownieinmotion-and-locq). – BrownieInMotion Nov 10 '20 at 01:54
  • For anyone lost here, the `json.dumps(data)` can't just be printed, it needs to be stored and then sent. The dumps is to put it back into json format, as the edit done with the str() will not include the double quote. – doublespaces Aug 31 '22 at 20:18