'How to add an entry to firebase using requests module?
I have a firebase database that holds a list of words, so has structure like this:
words_to_add
--words
----0:'hello'
----1:'goodbye'
so basically its {words: ['hello','goodbye']}.
I want to add to this dictionary so that its holds additional words.
I have tried to use requests.patch("Firebase_URL", data= '{"words":"[new_list_of_words]"}' and with requests.put() but they overwrite the contents of words to a string of the list which isn't what I want. How could I just add another entry to list?
Solution 1:[1]
A path request to the REST API of the Realtime Database takes each key in the dictionary you pass to it and writes the value from your request into the database for that key. Since you specify words as the key, all existing words will be replaced.
You can perform a deep update by providing a path as the key, so for example data= '{"words/2": "banana", "words/3": "pie"}'. Although I haven't tested this on arrays, it should add the second and third element to the array.
The problem with this is of course is that you'd have to know (and agree with any other users) on how many items there currently are in the array, leading to all kinds of possible problems. This is one of the many reasons that Firebase recommends against using arrays in it's vintage blog post: Best Practices: Arrays in Firebase.
In this case, the better structure would be to use a map like his for the words in your database:
words: {
"hello": true,
"goodbye": true
}
The true value here is just needed since Firebase won't store a key without a value and has no real meaning.
Now that we have a map of words, you can path it with:
requests.patch("Firebase_URL", data='{"words/banana":true, "words/pie":true}'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
