-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
155 lines (127 loc) · 4.99 KB
/
api_client.py
File metadata and controls
155 lines (127 loc) · 4.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import requests
import base64
import json
class CROApiClient:
"""
Client for interacting with the CRO (Companies Registration Office) API.
"""
BASE_URL = "https://services.cro.ie/cws"
def __init__(self, email, api_key):
"""
Initialize the API client with credentials.
Args:
email (str): The email address for API authentication
api_key (str): The API key for authentication
"""
self.email = email
self.api_key = api_key
# Create the base64 encoded auth header
auth_string = f"{email}:{api_key}"
self.auth_header = base64.b64encode(auth_string.encode("utf-8")).decode("utf-8")
def _get_headers(self):
"""
Get the common headers for API requests.
Returns:
dict: Headers for API requests
"""
return {
"Authorization": f"Basic {self.auth_header}",
"Accept": "application/json"
}
def _handle_response(self, response):
"""
Handle the API response and check for errors.
Args:
response (Response): The response from the API
Returns:
dict: The JSON response data
Raises:
Exception: If the API returns an error
"""
if response.status_code != 200:
try:
error_data = response.json()
error_message = error_data.get("message", "Unknown error")
except ValueError:
error_message = response.text
raise Exception(f"API Error ({response.status_code}): {error_message}")
# Parse the JSON response
data = response.json()
# Handle different response formats
if isinstance(data, list):
# Convert list response to dict format for consistency
return {"companies": data, "total_results": len(data)}
return data
def check_status(self):
"""
Check if the CRO API services are running.
Returns:
bool: True if services are running, False otherwise
"""
response = requests.get(
f"{self.BASE_URL}/status",
headers=self._get_headers()
)
data = self._handle_response(response)
return data.get("ServicesRunning", False)
def search_companies(self, company_name=None, company_num=None, company_bus_ind="e",
search_type=3, address=None, skip=0, max_results=10,
sort_by=None, sort_dir=None):
"""
Search for companies using various parameters.
Args:
company_name (str, optional): Part of company/business name (min 3 characters)
company_num (str, optional): Company or business number
company_bus_ind (str, optional): Filter by type (C=companies, B=business names, E=both)
search_type (int, optional): 1=Exact match, 2=Starts with, 3=Contains
address (str, optional): Any part of address to narrow results
skip (int, optional): Number of rows to skip (for pagination)
max_results (int, optional): Maximum rows to return
sort_by (str, optional): Field to sort by
sort_dir (str, optional): ASC or DESC
Returns:
dict: Search results
"""
params = {
"format": "json"
}
# Add optional parameters if provided
if company_name:
params["company_name"] = company_name
if company_num:
params["company_num"] = company_num
if company_bus_ind:
params["company_bus_ind"] = company_bus_ind
if search_type:
params["searchType"] = search_type
if address:
params["address"] = address
if skip:
params["skip"] = skip
if max_results:
params["max"] = max_results
if sort_by:
params["sortBy"] = sort_by
if sort_dir:
params["sortDir"] = sort_dir
response = requests.get(
f"{self.BASE_URL}/companies",
params=params,
headers=self._get_headers()
)
return self._handle_response(response)
def get_company_details(self, company_number, company_bus_ind):
"""
Get detailed information about a specific company.
Args:
company_number (str): The company number
company_bus_ind (str): The company business indicator (c or b)
Returns:
dict: Company details
"""
response = requests.get(
f"{self.BASE_URL}/company/{company_number}/{company_bus_ind}",
params={"format": "json"},
headers=self._get_headers()
)
return self._handle_response(response)