@@ -16,39 +16,35 @@ def lookup(
1616 ):
1717 params = {}
1818
19- # API key (optional, API handles missing key response)
2019 if self .api_key :
2120 params ["key" ] = self .api_key
2221
23- # format is optional (defaults to JSON if not provided)
2422 if format :
2523 params ["format" ] = format
2624
27- # callback only valid for jsonp
2825 if callback :
2926 if format != "jsonp" :
3027 raise ValueError ("callback can only be used when format='jsonp'" )
3128 params ["callback" ] = callback
3229
3330 url = f"{ self .BASE_URL } /{ ip } " if ip else self .BASE_URL
3431
35- response = requests .get (url , params = params , timeout = self .timeout )
36-
37- # HTTP-level error (network / server)
38- if not response .ok :
39- raise RuntimeError (
40- f"Ip2Geo API error { response .status_code } : { response .text } "
32+ try :
33+ response = requests .get (
34+ url ,
35+ params = params ,
36+ timeout = self .timeout ,
4137 )
42-
43- # JSON response handling
44- if format in ( None , "json" ):
45- data = response . json ()
46-
47- if not data . get ( "success" , False ) :
48- # API-level error (eg: missing API key)
49- raise RuntimeError ( data . get ( "error" , "Unknown API error" ) )
50-
51- return data
52-
53- # Non-JSON formats return raw text
38+ except requests . RequestException as e :
39+ # TRUE transport failure
40+ raise RuntimeError ( "Unable to reach Ip2Geo API" ) from e
41+
42+ # If JSON is expected (default or explicit)
43+ if format is None or format == "json" :
44+ try :
45+ return response . json ( )
46+ except ValueError :
47+ raise RuntimeError ( "Expected JSON but received invalid response" )
48+
49+ # XML / YAML / JSONP → raw text
5450 return response .text
0 commit comments