Based on the official API documentation, I've created a more robust implementation that handles the API's specific requirements and structures. Here's the enhanced solution:
python
import requests
import pandas as pd
from typing import Dict, List, Optional, Tuple
import time
import json
import urllib.parse
class EUFundingPortalAPI:
"""
Client for EU Funding & Tenders Opportunities Portal API
Documentation: https://ec.europa.eu/info/funding-tenders/opportunities/portal/screen/support/apis
"""
BASE_URL = "https://webgate.ec.europa.eu/funding-tenders-opportunities/octf/opportunity/projects/"
def __init__(self, timeout=30, max_retries=3, delay=0.5):
self.session = requests.Session()
self.timeout = timeout
self.max_retries = max_retries
self.delay = delay
self.session.headers.update({
"Accept": "application/json",
"User-Agent": "EU-Funding-Research/1.0 (https://example.com/research)",
"Content-Type": "application/json"
})
def _call_api(self, endpoint: str, params: Optional[dict] = None, payload: Optional[dict] = None) -> dict:
"""Internal method to handle API requests with retries"""
url = f"{self.BASE_URL}{endpoint}"
for attempt in range(self.max_retries):
try:
if payload:
response = self.session.post(url, params=params, json=payload, timeout=self.timeout)
else:
response = self.session.get(url, params=params, timeout=self.timeout)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt < self.max_retries - 1:
time.sleep(self.delay * (2 ** attempt))
continue
raise RuntimeError(f"API request failed: {str(e)}") from e
finally:
time.sleep(self.delay) # Basic rate limiting
def search_project(self,
project_code: Optional[str] = None,
acronym: Optional[str] = None) -> List[dict]:
"""Search projects by code or acronym using the search API"""
if not project_code and not acronym:
raise ValueError("Must provide either project_code or acronym")
# Prepare the search query according to API documentation
query = {
"criteria": {
"operator": "OR",
"criterias": []
},
"sort": [{"field": "lastUpdateDate", "order": "DESC"}],
"page": 1,
"pageSize": 10
}
if project_code:
query["criteria"]["criterias"].append({
"field": "reference",
"operator": "EQUALS",
"value": project_code
})
if acronym:
query["criteria"]["criterias"].append({
"field": "acronym",
"operator": "CONTAINS",
"value": acronym
})
endpoint = "search"
results = self._call_api(endpoint, payload=query)
return results.get('content', [])
def get_project_details(self, project_id: str) -> dict:
"""Get full project details by ID"""
endpoint = f"details/{project_id}"
return self._call_api(endpoint)
def get_project_partners(self, project_id: str) -> List[dict]:
"""Get project participants/partners"""
endpoint = f"participants/{project_id}"
return self._call_api(endpoint)
def fetch_project_data(self,
project_code: Optional[str] = None,
acronym: Optional[str] = None) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Main method to fetch complete project data:
1. Search for project(s)
2. Retrieve project details
3. Get participants information
4. Return structured DataFrames
Returns:
(project_df, participants_df)
"""
# Step 1: Search for projects
projects = self.search_project(project_code, acronym)
if not projects:
raise ValueError("No projects found with the given criteria")
# For simplicity, take the first match (project codes should be unique)
project = projects[0]
project_id = project['id']
# Step 2: Get project details
details = self.get_project_details(project_id)
# Step 3: Get participants
participants = self.get_project_partners(project_id)
# Step 4: Structure data for DataFrames
project_data = self._structure_project_data(project, details)
participants_data = self._structure_participants_data(participants)
return pd.DataFrame([project_data]), pd.DataFrame(participants_data)
def _structure_project_data(self, project: dict, details: dict) -> dict:
"""Extract relevant project information"""
# Get English text where available
def get_english(data):
if isinstance(data, dict):
return data.get('en', '')
return data
return {
"project_id": project.get('id'),
"project_code": project.get('reference'),
"acronym": project.get('acronym'),
"title": get_english(project.get('title')),
"programme": project.get('programme', {}).get('title', {}).get('en', ''),
"start_date": project.get('startDate'),
"end_date": project.get('endDate'),
"total_cost": project.get('totalCost'),
"ec_contribution": project.get('ecMaxContribution'),
"summary": get_english(details.get('objective')),
"call_identifier": project.get('callIdentifier'),
"topics": ", ".join([t.get('title', {}).get('en', '') for t in project.get('topics', [])]),
"status": project.get('status'),
"last_update": project.get('lastUpdateDate')
}
def _structure_participants_data(self, participants: list) -> List[dict]:
"""Structure participants information"""
return [{
"project_id": p.get('projectId'),
"organization_id": p.get('organisationId'),
"name": p.get('legalName'),
"short_name": p.get('shortName'),
"role": p.get('role'),
"activity_type": p.get('activityType', {}).get('description', {}).get('en', ''),
"country": p.get('country'),
"ec_contribution": p.get('ecContribution'),
"is_coordinator": p.get('coordinator')
} for p in participants]
# Example usage
if __name__ == "__main__":
api = EUFundingPortalAPI()
# Search by project code (exact match)
project_code = "101016894" # Replace with your project code
# Search by acronym (partial match)
# acronym = "GAIA-X"
try:
project_df, partners_df = api.fetch_project_data(project_code=project_code)
# project_df, partners_df = api.fetch_project_data(acronym=acronym)
print("\nPROJECT OVERVIEW:")
print(project_df[['project_code', 'acronym', 'title', 'ec_contribution', 'start_date', 'end_date']].to_string(index=False))
print("\nPROJECT SUMMARY:")
print(project_df['summary'].values[0])
print("\nPARTNERS:")
print(partners_df[['name', 'country', 'role', 'ec_contribution']].to_string(index=False))
# Save results to Excel
with pd.ExcelWriter('eu_funding_project.xlsx') as writer:
project_df.to_excel(writer, sheet_name='Project Overview', index=False)
partners_df.to_excel(writer, sheet_name='Partners', index=False)
print("\nResults saved to eu_funding_project.xlsx")
except Exception as e:
print(f"Error: {str(e)}")
Key improvements in this implementation:
API-Endpoint Compliant: Uses endpoints documented in the official API reference
Structured Search: Properly formats search queries with criteria objects
Replace project_code with your target project identifier
Run the script to get console output and Excel export
For bulk operations or additional fields, you can extend the search_project method to handle pagination (page and pageSize parameters) and add more fields to the extraction methods. The API documentation suggests additional available fields that can be incorporated as needed.
This implementation follows the API's best practices and handles the complex nested JSON structures returned by the EU Funding & Tenders portal.