GuideStar QuickStart Code Samples

Document created by communitymanager Administrator on Feb 26, 2016Last modified by communitymanager Administrator on Dec 1, 2016
Version 12Show Document
  • View in full screen mode

Connect to the API using cURL

curl -3 -u username:password https://quickstartdata.guidestar.org/v1/quickstartsearch?q=ein:54-1774039 

or

curl -3 -u apikey: https://quickstartdata.guidestar.org/v1/quickstartsearch?q=ein:54-1774039

Connect to the API using .NET

using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace C# API_Example
  class Program 
  {   
     static void Main(string[] args)   
     {      // Call the Search API and get information for the Organization with EIN = 54-1774039     
          string uri = "https://quickstartdata.guidestar.org/v1/quickstartsearch?q=ein:54-1774039";     
          string username_or_api_key = "<User Name or API Key here>";     
          string passwd = "<Password here - not needed if using an API Key>";     
          var req = WebRequest.Create(uri);     
          req.Credentials = new NetworkCredential(username_or_api_key, passwd);     
          req.Proxy = null;      var response = req.GetResponse();     
          using (Stream dataStream = response.GetResponseStream())     
          {       
               using (StreamReader reader = new StreamReader(dataStream))       
               {         
                    string responseFromServer = reader.ReadToEnd();         
                    Console.WriteLine(responseFromServer);       
               }     
          }     
          Console.ReadKey();     
          response.Close();   
     } 
}

 

Connect to the API using Java

This example makes use of the Apache HttpClient library 4.1 to simplify http requests. To use this library, download the binaries with dependencies from http://hc.apache.org/ and add them to your project classpath. Include your GuideStar credentials in place of the user:password.

This example makes use of the Apache HttpClient library 4.1 to simplify http requests. To use this library, download the binaries with dependencies from 
http://hc.apache.org/

and add them to your project classpath. Include your GuideStar credentials in place of the user:password.


package org.guidestar.data.api;

import java.io.IOException;

import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.apache.commons.codec.binary.Base64;

public class TestAPI {

          //this is the request string that calls the earch API.

     //Search for Organizations in the 23188 zip code and return 25 results.

          private static String request = "https://data.guidestar.org/v1/search?q=zip:23188&r=25
";

          public static void main(String[] args) throws ClientProtocolException, IOException {

                    //encode login credentials

                    byte[] encodedBytes = Base64.encodeBase64(username + ":" + password.getBytes());

                    //The recommended httpclient to use.

                    CloseableHttpClient httpclient = HttpClients.createDefault();

                    HttpGet httpget = new HttpGet(request);

                    //Set the authorization header with the GuideStar API credentials

                    httpget.setHeader("Authorization","Basic " + new String(encodedBytes));

                    //The recommended response object to use.

                    CloseableHttpResponse response = httpclient.execute(httpget);

                    //We want to try and get an entity back from the response to our request try

                    {

                               HttpEntity entity = response.getEntity();

                               if (entity != null) {

                                         System.out.println(EntityUtils.toString(entity));

                               }

                    }

                    catch(Exception e) {

                              e.printStackTrace();

                    } finally {     //close the response object and client object

                               response.close();

                               httpclient.close();

                    }

           }

}


Connect to the API using JavaScript and jQuery

(Please note that it is possible to modify the authentication header to include your GuideStar credentials)

beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", “Basic“ + hash(username + “:” + password) ); }

 

Connect to the API using Ruby

require 'net/http' 
uri = URI('https://quickstartdata.guidestar.org/v1/quickstartsearch?q=ein:54-1774039') 
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https',
     :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
     request = Net::HTTP::Get.new uri.request_uri
     request.basic_auth 'username', 'password'
     response = http.request request # Net::HTTPResponse object
     puts response.body
end

 

Connect to the API using PHP

 

<!DOCTYPE html>
<html>
<body>

<h1>PHP GuideStar Search API Test</h1>

<?php
// call the GuideStar Search v 1_1 API and search on the term "guidestar".
// Specify the return results to be delivered in JSON format.
$url = 'https://quickstartdata.guidestar.org/v1/quickstartsearch?q=ein:54-1774039

';


echo '<h2>URL: ==> '. $url. "</h2>";
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//Set options required by HTTPS
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_USERPWD, "<user name or api key>:<password - blank if API key is used>");
curl_setopt($curl , CURLOPT_SSL_VERIFYPEER , false );
curl_setopt($curl , CURLOPT_SSL_VERIFYHOST , false );
$output = curl_exec($curl);

if (curl_errno($curl))
{
  echo 'Curl Error: ' .curl_error($curl);
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additional info: ' . var_export($info));
}

curl_close($curl);
print "Decoded JSON:<br>";

//JSON decoding in PHP only works for UTF-8 encoded text
$decoded = json_decode($output, true );

if(json_last_error() != JSON_ERROR_NONE)
    switch (json_last_error())
  {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

// The JSON return data may include nested arrays. In the Search API, the search "hits"
// are themselves an array, so we process the result using a recursive function that will
// display nested arrays to any depth.

printNestedArray($decoded);
echo '<br>response ok!';

// Echo each key:value in the array. If the 'value' is an array,
//call the function recursively
function printNestedArray($a) {
    echo '<blockquote>';
    foreach ($a as $key => $value) {
      echo htmlspecialchars("$key: ");
      if (is_array($value)) {
        printNestedArray($value);
      } else {
        echo htmlspecialchars($value) . '<br />';
      }
    }
    echo '</blockquote>';
  }?>


</body>
</html>

Attachments

    Outcomes