Skip to content

Commit f86ca67

Browse files
committed
fix examples
1 parent 21eaf9b commit f86ca67

File tree

10 files changed

+552
-584
lines changed

10 files changed

+552
-584
lines changed

examples/check_domain.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import argparse
1111

1212
from namecheap import NamecheapClient
13-
from utils.print_table import print_table
13+
from examples.utils.print_table import print_table
1414

1515
# Parse command line arguments
1616
parser = argparse.ArgumentParser(
@@ -23,20 +23,22 @@
2323

2424
# Create the Namecheap client and check domain availability
2525
client = NamecheapClient(
26-
api_user="default",
27-
api_key="default",
28-
username="default",
29-
client_ip="default",
3026
debug=args.debug,
27+
load_env=True # Load values from .env file
3128
)
3229
result = client.enhanced.domains.check_with_pricing(args.domains)
3330

31+
if args.debug:
32+
import json
33+
print("\nRaw API response structure:")
34+
print(json.dumps(result, indent=2, default=str))
35+
3436
# Prepare table data
3537
headers = ["Domain", "Available", "Premium", "Price"]
3638
rows = []
3739

38-
# The result now contains a DomainCheckResult key with a list of domain results
39-
domains = result["DomainCheckResult"]
40+
# The result contains a DomainCheckResult key with a list of domain results
41+
domains = result.get("DomainCheckResult", [])
4042

4143
for domain in domains:
4244
available = "Yes" if domain.get("Available") else "No"

examples/dns_tool.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,7 @@ def list_records(
7676

7777
# Get records now returns a clean list of normalized records
7878
records = client.domains.dns.get_hosts(domain)
79-
return records
80-
79+
8180
if client.debug:
8281
print(f"\nFound {len(records)} DNS records")
8382

@@ -95,11 +94,11 @@ def list_records(
9594

9695
for record in records:
9796
# Use the original API field names
98-
name = record["Name"]
99-
record_type = record["Type"]
100-
ttl = record["TTL"]
101-
mx_pref = record["MXPref"] if record_type == "MX" else ""
102-
address = record["Address"]
97+
name = record.get("Name", "")
98+
record_type = record.get("Type", "")
99+
ttl = record.get("TTL", "")
100+
mx_pref = record.get("MXPref", "") if record_type == "MX" else ""
101+
address = record.get("Address", "")
103102

104103
rows.append(
105104
[str(name), str(record_type), str(ttl), str(mx_pref), str(address)]
@@ -108,6 +107,8 @@ def list_records(
108107
# Print table
109108
print(f"\nDNS Records for {domain}:")
110109
print_table(headers, rows)
110+
111+
return records
111112

112113
except NamecheapException as e:
113114
print(e)
@@ -154,12 +155,12 @@ def add_record(
154155
# Update the records
155156
result = client.domains.dns.set_hosts(domain, updated_records)
156157

157-
if result["success"]:
158+
# Check for success based on IsSuccess field which is normalized to "IsSuccess"
159+
if result.get("IsSuccess", False):
158160
print(f"\nSuccess! Record added to {domain}")
159161
else:
160-
print(
161-
f"\nWarning: Operation completed but with warnings: {result['warnings']}"
162-
)
162+
warnings = result.get("Warnings", "")
163+
print(f"\nWarning: Operation completed but with warnings: {warnings}")
163164

164165
except NamecheapException as e:
165166
print(e)
@@ -219,13 +220,15 @@ def delete_record(
219220
# Update records (removing the ones to delete)
220221
result = client.domains.dns.set_hosts(domain, records_to_keep)
221222

222-
if result["success"]:
223+
# Check for success based on IsSuccess field
224+
if result.get("IsSuccess", False):
223225
print(
224226
f"\nSuccess! {len(records_to_delete)} record(s) deleted from {domain}"
225227
)
226228
else:
229+
warnings = result.get("Warnings", "")
227230
print(
228-
f"\nWarning: Operation completed but with warnings: {result['warnings']}"
231+
f"\nWarning: Operation completed but with warnings: {warnings}"
229232
)
230233

231234
except NamecheapException as e:
@@ -385,13 +388,10 @@ def main() -> None:
385388

386389
args = parser.parse_args()
387390

388-
# Initialize client with debug mode using the args object
391+
# Initialize client with debug mode and load credentials from environment variables
389392
client = NamecheapClient(
390-
api_user="default",
391-
api_key="default",
392-
username="default",
393-
client_ip="default",
394393
debug=args.debug,
394+
load_env=True
395395
)
396396

397397
# Execute the appropriate command

namecheap/api/domains/base.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,10 @@ def check(self, domains: List[str]) -> List[Dict[str, object]]:
170170

171171
# Use the normalize_api_response method to get results
172172
results = self.client.normalize_api_response(
173-
response=response, result_key="DomainCheckResult", return_type="list"
173+
response=response,
174+
result_key="DomainCheckResult",
175+
boolean_fields=["Available", "IsPremiumName"],
176+
return_type="list"
174177
)
175178

176179
# Results are now properly typed as ResponseList (List[Dict[str, object]])

namecheap/api/users/base.py

Lines changed: 12 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
Users API operations
33
"""
44

5-
from typing import Any, List, Optional, TypedDict
5+
from typing import Any, List, Optional, TypedDict, Union
6+
7+
# Import ResponseDict type from base module for type annotations
8+
from ...base import ResponseDict
69

710

811
# TypedDict definitions for user operations
@@ -87,8 +90,8 @@ def get_pricing(
8790
product_category: Optional[str] = None,
8891
promotion_code: Optional[str] = None,
8992
action_name: Optional[str] = None,
90-
product_name: Optional[List[str]] = None,
91-
) -> PricingResult:
93+
product_name: Optional[Union[str, List[str]]] = None,
94+
) -> ResponseDict:
9295
"""
9396
Get pricing information for Namecheap products
9497
@@ -103,10 +106,10 @@ def get_pricing(
103106
product_category: Product category (REGISTER, RENEW, REACTIVATE, TRANSFER, WHOISGUARD)
104107
promotion_code: Promotional (coupon) code for the product
105108
action_name: Name of the action (REGISTER, RENEW, REACTIVATE, TRANSFER, WHOISGUARD)
106-
product_name: List of product names (e.g., [".com", ".net"] for domains)
109+
product_name: List or single product name (e.g., ".com" or [".com", ".net"] for domains)
107110
108111
Returns:
109-
Dictionary with pricing information
112+
Raw response dictionary directly from the API with complete XML structure preserved
110113
111114
Raises:
112115
ValueError: If parameters are invalid
@@ -169,75 +172,17 @@ def get_pricing(
169172
params["ProductName"] = product_name
170173

171174
# Make the API call with centralized error handling
175+
# This returns the raw CommandResponse section from the API response
172176
response = self.client._make_request(
173177
"namecheap.users.getPricing",
174178
params,
175179
error_codes,
176180
{"product_type": product_type},
177181
)
178182

179-
# Parse the response into a properly typed result
180-
product_list: List[ProductPrice] = []
181-
182-
# Extract products from the response
183-
if "ProductType" in response and "ProductCategory" in response.get(
184-
"ProductType", {}
185-
):
186-
categories = response["ProductType"]["ProductCategory"]
187-
if not isinstance(categories, list):
188-
categories = [categories]
189-
190-
for category in categories:
191-
if "Product" in category:
192-
products = category["Product"]
193-
if not isinstance(products, list):
194-
products = [products]
195-
196-
for product in products:
197-
if isinstance(product, dict):
198-
product_price: ProductPrice = {
199-
"ProductName": product.get("Name", ""),
200-
"Currency": product.get("Currency", "USD"),
201-
}
202-
203-
# Add prices if available
204-
if "Price" in product:
205-
product_price["Price"] = float(product["Price"])
206-
207-
# Add specific price types if available
208-
if "RegisterPrice" in product:
209-
product_price["RegisterPrice"] = float(
210-
product["RegisterPrice"]
211-
)
212-
if "RenewPrice" in product:
213-
product_price["RenewPrice"] = float(
214-
product["RenewPrice"]
215-
)
216-
if "TransferPrice" in product:
217-
product_price["TransferPrice"] = float(
218-
product["TransferPrice"]
219-
)
220-
if "RestorePrice" in product:
221-
product_price["RestorePrice"] = float(
222-
product["RestorePrice"]
223-
)
224-
if "ReactivatePrice" in product:
225-
product_price["ReactivatePrice"] = float(
226-
product["ReactivatePrice"]
227-
)
228-
229-
product_list.append(product_price)
230-
231-
# Create the typed result
232-
result: PricingResult = {
233-
"products": product_list,
234-
"currency": response.get("Currency", "USD"),
235-
"product_type": product_type,
236-
"category": product_category,
237-
"promotion_code": promotion_code,
238-
}
239-
240-
return result
183+
# Return the raw response to allow enhanced methods to parse it according to their needs
184+
# This preserves the original XML structure mapping
185+
return response
241186

242187
def get_balances(self) -> AccountBalance:
243188
"""

0 commit comments

Comments
 (0)