Using the Gender API

In the past months I searched the web for APIs to play with. I found quite a few that I wanted to try out. Some of them are actually useful, others not so much. In the coming weeks I will be showcasing interesting, useful or fun ones I found.

Without further ado, I present you the Gender API. It's a neat little gem that can detect a gender by first name or even an e-mailaddress. There are several options which can increase the accuracy, like location or language. For example we could ask for the gender of someone named "Bram" and it will return "male".

That's actually quite handy! You can use it for registration forms to fill the gender for the user, so he can proceed with more important steps. Or what about contact forms? You can be pretty sure you are talking to an actual sir or madam, instead of either one (Dear Sir or Madam). It's atleast a little bit more personal.

Gender API delivers a straightforward API that is easy to implement and understand. And making things easier for you, I wrote a tiny PHP wrapper. It's usable, although there is room for improvement.

Ofcourse there are more examples of APIs like this, for example we have Genderize.io or iGender. But I prefer Gender API, mainly because they give the option to detect location by IP address. Supply them with an IP address and the accuracy is increased instantaneously. For example if we would search for "Andrea" in Germany the result will be "female", but search for it in Italy and you will get "male".

Below you can find some examples of how to use this PHP wrapper. If you like this leave a message in my contact form, since comments aren't available yet ;)

The code

Usage

You can easily use it like this:

// Instantiate new GenderGuess object.
$genderGuesser = new GenderGuess();

// Give me the gender.
try {
  $gender = $genderGuesser->guessGender('Bram ten Hove', $ipaddress);
} catch (Exception $e) {
  $gender = 'Error occured, no detection possible.';
}

Some examples

$genderGuesser = new GenderGuess();
$genderGuesser->guessGender('Bram ten Hove');

Returns "male".

$genderGuesser = new GenderGuess();
$genderGuesser->guessGender('Renee');

Returns "male".

$genderGuesser = new GenderGuess();
$genderGuesser->guessGender('Andrea', '2.119.255.255'); // Italy.

Returns "male".

$genderGuesser = new GenderGuess();
$genderGuesser->guessGender('saqwdas');

Returns "unknown".

$genderGuesser = new GenderGuess();
$genderGuesser->guessGender('A.');

Throws an exception because of an unusable first name.

The class with functions

/**
 * File contains the GenderGuess class which can detect genders by names.
 *
 * @author     Bram ten Hove
 * @license    http://opensource.org/licenses/MIT  MIT License
 */

 class GenderGuess {
  /**
   * Function that tries to guess the gender by full name.
   *
   * @param string $fullname
   *   The full name we want to detect the gender of.
   * @param string $ipaddress
   *   Optional IP address we can use for better detection.
   *
   * @return string
   *   Either female, male or unknown.
   */
  public function guessGender($fullname, $ipaddress = null) {
    // Throw new exception if full name is not given or empty.
    if (empty($fullname) && !is_string($fullname)) {
      throw new Exception('No name given.');
    }

    // Get first name from full name.
    try {
      $firstname = $this->getFirstName($fullname);
    } catch (Exception $e) {
      throw new Exception('Invalid first name.');
    }

    // Send the request.
    try {
      $gender = $this->sendRequest($firstname, $ipaddress);

      // Return the gender.
      return $gender;
    } catch (Exception $e) {
      return 'unknown';
    }
  }

  /**
   * Function to get the first name from a full name.
   *
   * @param string $fullname
   *   The full name we have to get the first name from.
   *
   * @return string
   *   The first name.
   */
  public function getFirstName($fullname) {
    // Remove any dots (e.g. J. Doe become J Doe).
    $fullname = str_replace('.', '', $fullname);

    // Explode into first name and the rest.
    $pieces = explode(' ', $fullname);

    // Check if we're dealing with a name we cannot use.
    if (strlen($pieces[0]) < 2) {
      throw new Exception('Invalid first name.');
    }
    else {
      // Return the first name.
      return $pieces[0];
    }
  }

  /**
   * Function that makes a request to the Gender API.
   *
   * @param string $firstname
   *   The first name we will try to detect the gender of.
   * @param string $ipaddress
   *   Optional IP address we can use for better detection.
   *
   * @return string
   *   Either female, male or unknown.
   */
  private function sendRequest($firstname, $ipaddress = null) {
    $request_path = 'https://gender-api.com/get?name=' . urlencode($firstname);

    if (filter_var($ipaddress, FILTER_VALIDATE_IP)) {
      $request_path .= '&ip=' . $ipaddress;
    }

    // Make the API request.
    $ch = curl_init($request_path);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // The result from Gender API.
    $result = json_decode(curl_exec($ch));

    // Close curl request.
    curl_close($ch);

    // Detect proper result.
    if (!isset($result->errno)) {
      // Return the detected gender.
      return $result->gender;
    }
    else {
      throw new Exception('Error in inquiry result.');
    }
  }
}
#2