1+ import requests , json
2+ from pygments import highlight , lexers , formatters
3+
4+ class ApiTesting ():
5+ default_url = "https://127.0.0.1:8000"
6+
7+ # Make GET request
8+ @classmethod
9+ def get_request (cls ):
10+ request_url = cls .default_url
11+ input_url = input ('Enter URL: ' )
12+ if input_url != '' :
13+ request_url = input_url
14+
15+ # Check whether the request_url has an endpoint or not
16+ has_endpoint = cls .__check_endpoint (request_url )
17+
18+ # Check if http:// or https:// is present in request_url
19+ has_protocol = cls .__check_protocol (request_url )
20+
21+ if not (has_protocol ):
22+ request_url = "https://" + request_url
23+
24+ # Ask the user for endpoint if not present in request_url
25+ if not (has_endpoint ):
26+ if (request_url [- 1 ] == '/' ):
27+ endpoint = input ("Input endpoint (Without the starting slash): " )
28+ else :
29+ endpoint = input ("Input endpoint (With the starting slash): " )
30+ request_url += endpoint
31+
32+ print ("Trying ...\u26A1 " )
33+
34+ # Make GET request and store the response in response_data.json
35+ try :
36+ response = requests .get (request_url )
37+ print (f"Reponse Status Code: { response .status_code } " )
38+ response_data = json .loads (response .content )
39+ parsed_json = json .dumps (response_data , indent = 4 )
40+ output_json = highlight (parsed_json , lexers .JsonLexer (), formatters .TerminalFormatter ())
41+ print (output_json )
42+
43+ store_data = input ('Store response data? (Y/N): ' )
44+ if (store_data == 'Y' or store_data == 'y' ):
45+ with open ('response_data.json' , 'w' ) as jsonFile :
46+ json .dump (response_data , jsonFile , indent = 4 )
47+ print ("Response data stored in response_data.json" )
48+
49+ except requests .exceptions .InvalidSchema :
50+ print ("Check whether the URL is valid or check if the localhost server is active or not" )
51+ except Exception as e :
52+ print (e )
53+
54+ @classmethod
55+ def __check_endpoint (cls , request_url ):
56+ if (request_url == cls .default_url ):
57+ return False
58+ else :
59+ return True
60+
61+ @classmethod
62+ def __check_protocol (cls , request_url ):
63+ if (request_url [:4 ] == 'http' ):
64+ return True
65+ else :
66+ return False
0 commit comments