{"library":"firebase-admin","code":"import os\nimport firebase_admin\nfrom firebase_admin import credentials, firestore\n\n# Best practice: store service account key in an environment variable\n# and load it, or use Application Default Credentials on Google Cloud.\n# Replace 'path/to/your/serviceAccountKey.json' with actual path if not using env var.\nSERVICE_ACCOUNT_KEY_PATH = os.environ.get('FIREBASE_SERVICE_ACCOUNT_KEY_PATH', '')\n\nif SERVICE_ACCOUNT_KEY_PATH:\n    cred = credentials.Certificate(SERVICE_ACCOUNT_KEY_PATH)\nelse:\n    # Fallback for Google Cloud environments where ADC are available\n    # or if you prefer not to use a file directly for local testing\n    cred = credentials.ApplicationDefault()\n\n# Initialize the app\nfirebase_admin.initialize_app(cred, {\n    'projectId': os.environ.get('FIREBASE_PROJECT_ID', 'your-project-id'),\n    'databaseURL': os.environ.get('FIREBASE_DATABASE_URL', 'https://your-project-id.firebaseio.com')\n})\n\ndb = firestore.client()\n\n# Add data to Firestore\ndoc_ref = db.collection('users').document('alovelace')\ndoc_ref.set({\n    'first': 'Ada',\n    'last': 'Lovelace',\n    'born': 1815\n})\nprint(f\"Added document with ID: {doc_ref.id}\")\n\n# Read data from Firestore\nusers_ref = db.collection('users')\ndocs = users_ref.stream()\n\nprint(\"\\nAll users:\")\nfor doc in docs:\n    print(f\"{doc.id} => {doc.to_dict()}\")\n\n# Clean up (optional, for demonstration purposes)\n# firebase_admin.delete_app(firebase_admin.get_app())\n","lang":"python","description":"Initializes the Firebase Admin SDK using service account credentials (preferably from an environment variable) or Application Default Credentials. It then demonstrates connecting to Cloud Firestore, adding a new document to a collection, and reading all documents from that collection. Remember to replace placeholder project IDs and URLs, and secure your service account key.","tag":null,"tag_description":null,"last_tested":"2026-04-24","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}