Python Forum
Need help with a Basic API Query.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with a Basic API Query.
#1


First of all I'm not a python coder, really don't know much about the language except that it's really powerful and one of the best languages anyone can learn. But, unfortunately, I choose the evil Microsoft .NET path a long time ago.

Anyway, I'm trying to help a friend provide some examples in other languages to help users get started more quickly using the API for his Email Validator.

The is the .NET code snippet.

          try {
	                string apiKey = "Your Secret Key";
	                string emailToValidate = "[email protected]";
                    string responseString = "";
                    string apiURL = "https://api.zerobounce.net/v1/validate?apikey=" + apiKey + "&email=" +  HttpUtility.UrlEncode(emailToValidate);

                            //Uncomment out to use the optional API with IP Lookup
                            //string apiURL = "https://api.zerobounce.net/v1/validatewithip?apikey=" + apiKey + "&email=" +  HttpUility.UrlEncode(emailToValidate); + "&ipaddress=" + HttpUtility.UrlEncode("99.123.12.122")

                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
	                    request.Timeout = 150000;
	                    request.Method = "GET";

	                    using (WebResponse response = request.GetResponse())
                        {
	                        response.GetResponseStream().ReadTimeout = 20000;
	                        using (StreamReader ostream = new StreamReader(response.GetResponseStream()))
                            {
	                            responseString = ostream.ReadToEnd();
		                    }
	                    }
                        } catch (exception ex) {
	                //Catch Exception - All errors will be shown here - if there are issues with the API
                    }
After doing a ton of searches in google, I came up with the follow, I'm not sure if it's 100% correct or what tweaks I need to make. Because I'm not running it. I was hoping one of you can take the time to modify it to make it accurate. Or if it's is accurate, let me know. I would like to put error handling in the code. I don't know how to do that or encode the email address.


# importing the requests library
import requests

# defining the api-endpoint 
API_ENDPOINT = "https://api.zerobounce.net/v1/validate"

# your API key here
API_KEY = "XXXXXXXXXXXXXXXXX"
EMAIL_TO_VALIDATE = "[email protected]"
# data to be sent to api
data = {'apikey':API_KEY,'email':EMAIL_TO_VALIDATE}

# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
Reply
#2
The C# code do a catch all error approach,with mixed in with time out.
It could look like this:
import requests

try:
    data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
    r = requests.post('http://httpbin.org/post', data=data, timeout=5)
    print(r.status_code)
    #print(r.text)
    r.raise_for_status()
except Exception as error:
    #Catch Exception All errors will be shown here if there are issues with the API
    print(f'There where a problem with connection {error}')
Http status will not make a Exception,but can force it with r.raise_for_status().
So if mistype http://httpbin.org/post999:
Error:
There where a problem with connection: 404 Client Error: NOT FOUND for url: http://httpbin.org/post999
See Errors and Exceptions.
TopCoder Wrote:I don't know how to do that or encode the email address.
What are you getting back?
Reply
#3
@snippsat

Thanks for the example, I'm trying to find a place online where I can run these code snippets. Everyplace, I find seems to be restricted and I get back this error.

Quote:ProxyError: HTTPSConnectionPool(host='api.zerobounce.net', port=443): Max retries exceeded with url: /v1/validate (Caused by
ProxyError('Cannot connect to proxy.', error('Tunnel connection failed: 403 Forbidden',)))

Does anyone know of an online emulator that a can test some sample code out that allows a HTTPS request?
Reply
#4
(Nov-27-2017, 03:50 PM)TopCoder Wrote: I find seems to be restricted and I get back this error.
Connection is okay,but doing stuff that is not allowed on server 403.
(Nov-27-2017, 03:50 PM)TopCoder Wrote: Does anyone know of an online emulator that a can test some sample code out that allows a HTTPS request?
I use httpbin in my code,which is a HTTP Request & Response Service.
>>> import requests
>>> data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
>>> r = requests.post('http://httpbin.org/post', data=data, timeout=5)
>>> r.status_code
200

>>> print(r.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "message": "We did it!", 
    "receiver": "Bob", 
    "sender": "Alice"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "46", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "85.165.243.249", 
  "url": "http://httpbin.org/post"
}

>>> r.headers
{'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 27 Nov 2017 17:47:07 GMT',
Content-Type': 'application/json',Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true',
X-Powered-By': 'Flask', 'X-Processed-Time': '0.00081205368042', 'Content-Length': '497', 'Via': '1.1 vegur'}

>>> r.headers['Date']
'Mon, 27 Nov 2017 17:47:07 GMT'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic SQL query using Py: Inserting or querying sqlite3 database not returning data marlonbown 3 1,364 Nov-08-2022, 07:16 PM
Last Post: marlonbown

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020