How to update Firestore document when data changes when collected from 3rd Party API instead of creating new document

Question:

The code below is set up to collect data from a 3rd party API for NBA games. At the moment it all works and the data is stored in GCP Firestore but the issue is that it creates a new document for each game every time you make an API call. So say it’s called 3 times a day there will be 3 different documents for the same game.

What I would like to happen is that each time the API is called and the game’s data has changed it updates the original document instead of creating a new one.

Any help would be appreciated.

import requests
import json
from firebase_admin import firestore

db = firestore.Client(project='xxxx')


def bluebet_nba_odds():
    # MAKE VARIABLES GLOBAL
    global away_team_win_odds, away_team, home_team_win_odds, home_team, start_time, event_title, event_id, competition

    # API CALL

    link = 'https://xxxxxxxxxx.com.au/json/reply/MasterCategoryRequest?EventTypeID=107&WithLevelledMarkets' 
           '=true&WithLevelledMarkets=true '
    # Request data from link as 'str'
    nbadata = requests.get(link).text
    # convert 'str' to Json
    nbadata = json.loads(nbadata)

    # JSON PARSE

    for nba_odds in nbadata['MasterCategories'][2]['Categories'][0]['MasterEvents']:
        competition = nba_odds['CategoryName']
        event_id = nba_odds['MasterEventId']
        event_title = nba_odds['MasterEventName']
        start_time = nba_odds['MaxAdvertisedStartTime']
        home_team = nba_odds['Markets'][0]['OutcomeName']
        home_team_win_odds = nba_odds['Markets'][0]['Price']
        away_team = nba_odds['Markets'][1]['OutcomeName']
        away_team_win_odds = nba_odds['Markets'][1]['Price']

# WRITE TO FIRESTORE

        data = {
            'competition': competition,
            'event_id': event_id,
            'event_title': event_title,
            'start_time': start_time,
            'home_team': home_team,
            'home_team_win_odds': home_team_win_odds,
            'away_team': away_team,
            'away_team_win_odds': away_team_win_odds,
            'timestamp': firestore.SERVER_TIMESTAMP,
            }

        db.collection('bluebet_nba_season_odds').document().set(data), print('Game Data Written to Firestore')


if __name__ == "__main__":
    bluebet_nba_odds()

Asked By: DrewS

||

Answers:

document() with no arguments generats a random document ID every time it’s called. Don’t do that. Give the document a name instead.

db.collection('bluebet_nba_season_odds').document('you-choose-a-name-here')

You might be helped by reviewing the API documentation to understand better how the API works, especially for the document() method that you’re calling.

Answered By: Doug Stevenson