policymap/api.py

81 lines
2.8 KiB
Python

from flask import Flask, request, jsonify
import requests
from neo4j import GraphDatabase
from dotenv import load_dotenv
import os
import logging
from cachetools import TTLCache
# Set up basic configuration for logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Load environment variables from .env file
load_dotenv()
# Retrieve Neo4j connection details and API key
NEO4J_URI = os.getenv('NEO4J_URI')
NEO4J_USER = os.getenv('NEO4J_USER')
NEO4J_PASSWORD = os.getenv('NEO4J_PASSWORD')
CONGRESS_API_KEY = os.getenv('CONGRESS_API_KEY')
if not NEO4J_URI or not NEO4J_USER or not NEO4J_PASSWORD:
raise ValueError("Neo4j connection details not found in .env file")
if not CONGRESS_API_KEY:
raise ValueError("Congress API key not found in .env file")
# Initialize Neo4j driver
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
# Initialize caches
neo4j_cache = TTLCache(maxsize=100, ttl=3600) # Cache for 1 hour
congress_api_cache = TTLCache(maxsize=100, ttl=3600) # Cache for 1 hour
app = Flask(__name__)
@app.route('/sponsored_legislation', methods=['GET'])
def get_sponsored_legislation():
bioguide_id = request.args.get('bioguideId')
if not bioguide_id:
return jsonify({"error": "bioguideId is required"}), 400
logger.info(f"Fetching sponsored legislation for member with bioguideId {bioguide_id}")
# Check cache before making API request
cached_legislation = congress_api_cache.get(bioguide_id)
if cached_legislation:
logger.info(f"Using cached sponsored legislation for bioguideId {bioguide_id}")
return jsonify({"message": "Sponsored legislation retrieved from cache", "legislations": cached_legislation})
@app.route('/persons', methods=['GET'])
def list_persons():
logger.info("Listing all person nodes from Neo4j")
# Check cache before querying Neo4j
cached_persons = neo4j_cache.get('all_persons')
if cached_persons:
logger.info("Using cached list of persons")
return jsonify({"message": "Persons retrieved from cache", "persons": cached_persons})
with driver.session() as session:
query = "MATCH (p:Person) RETURN p"
logger.info(f"Executing Neo4j query to list all person nodes: {query}")
result = session.run(query)
persons = [record['p'] for record in result]
person_list = []
for person in persons:
node_properties = {key: value for key, value in person.items()}
person_list.append(node_properties)
# Cache the response
neo4j_cache['all_persons'] = person_list
logger.info("Cached list of all persons")
return jsonify({"message": "Persons listed successfully", "persons": person_list})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)