View our
Email Score API Code Examples
Please read the API documentation before you start using our APIs in production.
The API key used in these examples is for demonstrative purposes and can be used only to check whoapi.com
PHP Code Example
Basic PHP example using cURL. First, we will send the email “goran@whoapi.com” for the scoring.
<?php
// Prepare vars
$email = "goran@whoapi.com"; // email to check
$r = "emailscore"; // API request type
$apikey = "demokey"; // your API key
// API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.whoapi.com/?email=$email&r=$r&apikey=$apikey");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = json_decode(curl_exec($ch), true);
curl_close($ch);
// Success
if (isset($output['status']) && $output['status'] == 0) {
echo "Success. Email \"$email\" was sent for the scoring.";
// API error
} elseif (!empty($output['status_desc'])) {
echo "API reports error: ".$output['status_desc'];
// Unknown error
} else {
echo "Unknown error";
}
?>
Second, we will request the scoring result.
<?php
// Prepare vars
$email = "goran@whoapi.com"; // email to check
$r = "emailscore-check"; // API request type
$apikey = "demokey"; // your API key
// API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.whoapi.com/?email=$email&r=$r&apikey=$apikey");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = json_decode(curl_exec($ch), true);
curl_close($ch);
// Success
if (isset($output['status']) && $output['status'] == 0) {
// The result is not yet ready
if (!isset($output['results'][0]['overall_score'])) {
echo "Success. Email \"$email\" is not yet scored. Try again later.";
} else {
echo "Success. Email \"$email\" was scored: ".$output['results'][0]['overall_score'];
}
// API error
} elseif (!empty($output['status_desc'])) {
echo "API reports error: ".$output['status_desc'];
// Unknown error
} else {
echo "Unknown error";
}
?>
JavaScript Code Example
First, we will send the email “goran@whoapi.com” for the scoring.
<script type="text/javascript">
var email = "goran@whoapi.com"; // email you want to check
var r = "emailscore"; // API request type
var apikey = "demokey"; // your API key
var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://api.whoapi.com/?email='+email+'&r='+r+'&apikey='+apikey, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
if (json.status == 0) {
document.getElementById("result").innerHTML = "Success. Email was sent for the scoring.";
} else {
document.getElementById("result").innerHTML = "API reports error: " + json.status_desc;
}
} else {
document.getElementById("result").innerHTML = "Unknown error";
}
};
xhr.send();
</script>
<div id="result">please wait...</div>
Second, we will request the scoring result.
<script type="text/javascript">
var email = "goran@whoapi.com"; // email you want to check
var r = "emailscore-check"; // API request type
var apikey = "demokey"; // your API key
var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://api.whoapi.com/?email='+email+'&r='+r+'&apikey='+apikey, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
if (json.status == 0) {
// The result is not yet ready
if (!json?.results[0]?.overall_score) {
document.getElementById("result").innerHTML = "Success. Email is not yet scored. Try again later";
} else {
document.getElementById("result").innerHTML = "Success. Email was scored: " + json.results[0].overall_score;
}
} else {
document.getElementById("result").innerHTML = "API reports error: " + json.status_desc;
}
} else {
document.getElementById("result").innerHTML = "Unknown error";
}
};
xhr.send();
</script>
<div id="result">please wait...</div>
Ruby Code Example
First, we will send the email “goran@whoapi.com” for the scoring.
require 'open-uri'
require 'json'
email = "goran@whoapi.com" # email to check
r = "emailscore" # API request type
apikey = "demokey" # your API key
output = JSON.parse(URI.open("https://api.whoapi.com/?email=#{email}&r=#{r}&apikey=#{apikey}").read)
if output["status"].to_i == 0
puts "Success. Email was sent for the scoring."
elsif !output["status_desc"].nil?
puts "API reports error: " + output["status_desc"]
else
puts "Unknown error"
end
Second, we will request the scoring result.
require 'open-uri'
require 'json'
email = "goran@whoapi.com" # email to check
r = "emailscore-check" # API request type
apikey = "demokey" # your API key
output = JSON.parse(URI.open("https://api.whoapi.com/?email=#{email}&r=#{r}&apikey=#{apikey}").read)
if output["status"].to_i == 0
if output["results"][0]["overall_score"].nil?
puts "Success. Email is not yet scored. Try again later"
elsif
puts "Success. Email was scored: " + output["results"][0]["overall_score"].to_s
end
elsif !output["status_desc"].nil?
puts "API reports error: " + output["status_desc"]
else
puts "Unknown error"
end
Python Code Example
First, we will send the email “goran@whoapi.com” for the scoring.
#!/usr/bin/env python
import requests
def whoapi_request(email, r, apikey) -> None:
res = requests.get('https://api.whoapi.com', dict(
email=email,
r=r,
apikey=apikey))
if res.status_code == 200:
data = res.json()
if int(data['status']) == 0:
print("Success. Email was sent for the scoring.")
else:
print("API reports error: " + data['status_desc'])
else:
raise Exception('Unexpected status code %d' % res.status_code)
email = 'goran@whoapi.com' # email to check
r = 'emailscore' # API request type
apikey = 'demokey' # key
whoapi_request(email, r, apikey)
Second, we will request the scoring result.
#!/usr/bin/env python
import requests
def whoapi_request(email, r, apikey) -> None:
res = requests.get('https://api.whoapi.com', dict(
email=email,
r=r,
apikey=apikey))
if res.status_code == 200:
data = res.json()
if int(data['status']) == 0:
if data["results"][0]["overall_score"] is None:
print("Success. Email is not yet scored. Try again later")
else:
print("Success. Email was scored: " + str(data["results"][0]["overall_score"]))
else:
print("API reports error: " + data['status_desc'])
else:
raise Exception('Unexpected status code %d' % res.status_code)
email = 'goran@whoapi.com' # email to check
r = 'emailscore-check' # API request type
apikey = 'demokey' # key
whoapi_request(email, r, apikey)
Objective C Code Example
First, we will send the email “goran@whoapi.com” for the scoring.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSString *email = @"goran@whoapi.com"; // email to check
NSString *r = @"emailscore"; // API request type
NSString *apikey = @"demokey"; // your API key
NSString *urlAsString = [NSString stringWithFormat:@
"https://api.whoapi.com/?email=%@&r=%@&apikey=%@", email, r, apikey];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlAsString]];
[urlRequest setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
// Semaphore used only for the debug purpose
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSNumber *status;
if([responseDictionary[@"status"] isKindOfClass:[NSString class]]) {
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
status = [f numberFromString:responseDictionary[@"status"]];
} else {
status = responseDictionary[@"status"];
}
if([status isEqualToNumber:@0])
{
NSLog(@"Success. Email was sent for the scoring.");
} else {
NSLog(@"API reports error: %@", responseDictionary[@"status_desc"]);
}
}
else
{
NSLog(@"Unexpected status code\n");
}
// Semaphore used only for the debug purpose
dispatch_semaphore_signal(sema);
}];
[dataTask resume];
// Semaphore used only for the debug purpose
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return 0;
}
Second, we will request the scoring result.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
NSString *email = @"goran@whoapi.com"; // email to check
NSString *r = @"emailscore-check"; // API request type
NSString *apikey = @"demokey"; // your API key
NSString *urlAsString = [NSString stringWithFormat:@
"https://api.whoapi.com/?email=%@&r=%@&apikey=%@", email, r, apikey];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlAsString]];
[urlRequest setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
// Semaphore used only for the debug purpose
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSNumber *status;
if([responseDictionary[@"status"] isKindOfClass:[NSString class]]) {
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
status = [f numberFromString:responseDictionary[@"status"]];
} else {
status = responseDictionary[@"status"];
}
if([status isEqualToNumber:@0])
{
if (responseDictionary[@"results"][0][@"overall_score"] == nil)
{
NSLog(@"Success. Email is not yet scored. Try again later\n");
} else {
NSLog(@"Success. Email was scored: %@", responseDictionary[@"results"][0][@"overall_score"]);
}
} else {
NSLog(@"API reports error: %@", responseDictionary[@"status_desc"]);
}
}
else
{
NSLog(@"Unexpected status code\n");
}
// Semaphore used only for the debug purpose
dispatch_semaphore_signal(sema);
}];
[dataTask resume];
// Semaphore used only for the debug purpose
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return 0;
}
C#(.NET) Code Example
First, we will send the email “goran@whoapi.com” for the scoring.
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
public class Program
{
public static void Main()
{
string apiType = "emailscore"; // API request type
string email = "goran@whoapi.com"; // email to check
string apiKey = "demokey"; // api key
WebRequest request = WebRequest.Create(String.Format("https://api.whoapi.com/?email={0}&r={1}&apikey={2}", email, apiType, apiKey));
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
JObject json = JObject.Parse(responseFromServer);
if (json.Value<int>("status") == 0)
{
Console.WriteLine("Success. Email was sent for the scoring.");
}
else
{
Console.WriteLine(String.Format("API reports error: {0}. ", json["status_desc"]));
}
}
}
Second, we will request the scoring result.
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
public class Program
{
public static void Main()
{
string apiType = "emailscore-check"; // API request type
string email = "goran@whoapi.com"; // email to check
string apiKey = "demokey"; // api key
WebRequest request = WebRequest.Create(String.Format("https://api.whoapi.com/?email={0}&r={1}&apikey={2}", email, apiType, apiKey));
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
JObject json = JObject.Parse(responseFromServer);
if (json.Value<int>("status") == 0)
{
if (json["results"][0]["overall_score"].Type == JTokenType.Null)
{
Console.WriteLine("Success. Email is not yet scored. Try again later");
}
else
{
Console.WriteLine(String.Format("Success. Email was scored: {0}. ", json["results"][0]["overall_score"]));
}
}
else
{
Console.WriteLine(String.Format("API reports error: {0}. ", json["status_desc"]));
}
}
}
Java Code Example
First, we will send the email “goran@whoapi.com” for the scoring.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
class Main {
public static void main(String args[]) {
try {
// Set data
String email = "goran@whoapi.com"; // email to check
String rtype = "emailscore"; // API request type
String apikey = "demokey"; // your API key
// Send request to API
URL obj = new URL("https://api.whoapi.com/?email=" + email + "&r=" + rtype + "&apikey=" + apikey);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Validate HTTP response code
int responseCode = con.getResponseCode();
if (responseCode != 200) {
System.out.println("HTTP request error, code: " + responseCode);
return;
}
// Read API reply
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get JSON
JSONObject myResponse = new JSONObject(response.toString());
int status = myResponse.getInt("status");
String statusDesc = myResponse.getString("status_desc");
// Validate request status
if (status != 0) {
System.out.println("API reports error: " + statusDesc);
return;
}
System.out.println("Success. Email was sent for the scoring.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Second, we will request the scoring result.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;
class Main {
public static void main(String args[]) {
try {
// Set data
String email = "goran@whoapi.com"; // email to check
String rtype = "emailscore-check"; // API request type
String apikey = "demokey"; // your API key
// Send request to API
URL obj = new URL("https://api.whoapi.com/?email=" + email + "&r=" + rtype + "&apikey=" + apikey);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Validate HTTP response code
int responseCode = con.getResponseCode();
if (responseCode != 200) {
System.out.println("HTTP request error, code: " + responseCode);
return;
}
// Read API reply
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get JSON
JSONObject myResponse = new JSONObject(response.toString());
int status = myResponse.getInt("status");
String statusDesc = myResponse.getString("status_desc");
// Validate request status
if (status != 0) {
System.out.println("API reports error: " + statusDesc);
return;
}
JSONArray results = myResponse.getJSONArray("results");
if (results.getJSONObject(0).isNull("overall_score")) {
System.out.println("Success. Email is not yet scored. Try again later");
} else {
int overallScore = results.getJSONObject(0).getInt("overall_score");
System.out.println("Success. Email was scored: " + overallScore);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Summary
The provided code examples demonstrate how to make API requests to the WhoAPI service for email scoring using different programming languages. The code examples use various HTTP client libraries (such as cURL, XMLHttpRequest, open-uri, requests, etc.) to send HTTP GET requests to the WhoAPI Email Score API endpoint.
The general flow of the code is as follows:
- It sets up the necessary variables, including the email address to check, the API request type (emailscore or emailscore-check), and the API key.
- It constructs the API request URL with the appropriate parameters.
- It sends an HTTP GET request to the API endpoint using the provided HTTP client library.
- It receives the API response and processes it.
- It handles different scenarios based on the response status.
For example, if the response status is 0, indicating success, the code may display a success message and retrieve the scoring result. If the response status is non-zero, indicating an error, the code may display an error message with the corresponding status description.
The examples demonstrate how to handle both the initial request to start the scoring process (emailscore) and the subsequent request to retrieve the scoring result (emailscore-check). The second request is required because scoring may take some time, and the result may not be available immediately.
It’s important to review the API documentation provided by WhoAPI to understand the available request types, response formats, and any specific requirements or limitations of the API.
Please note that the provided code snippets assume the availability of the WhoAPI service and may require modifications to the API endpoint or authentication mechanism if there are any changes to the service. It’s also important to use a valid API key provided by WhoAPI to authenticate the requests properly.