API Examples

Other APIs

  1. API Introduction
  2. Forms GET
  3. Fields GET
  4. Entries GET / POST
  5. Users GET
  6. Reports GET
  7. Widgets GET
  8. Comments GET
  9. Web Hooks PUT / DELETE
  10. Login POST
  11. Examples
  12. The Wufoo REST Principles


Introduction

To help jump-start your use of the API, we created templates for the most common actions that people take with the API. You may use these snippets in your own projects. We’ll be referencing sample code, which you may edit and use in your own projects.

Note that all these calls use the WufooCurl object, which is a helper class for API examples. You may use this object without understanding what it does, but to get a full grasp on what’s happening under the covers, feel free to read the WufooCurl class documentation.

Example: Get All Forms Snippet

This example shows you how to create a drop down containing the form name and form hash. The drop down will look like this.

Now that you know the goal of this exercise, let’s walk through this code. The first three lines instantiate a Wufoo Curl object and use this object to call the Forms API.

$curl = new WufooCurl();
$response = $curl->getAuthenticated('http://fishbowl.wufoo.com/api/v3/forms.json', self::API_KEY);
$response = json_decode($response);
echo $this->getFormsDropdownHtml($response->Forms);

The last line of the code above echos the result of the getFormsDropdownHtml function. This function simply takes in the $forms parameter as an array and loops over it, creating the HTML code to display a drop down box. Note how the form’s hash is added to the <option> tag’s value atribute. You can use this hash do do interesting stuff. For example, you can use the form hash to embed a form programmatically.

$str = '<select>';
if (count($forms)) {
    foreach ($forms as $form) {
        $str.= '<option value="'.$form->Hash.'">'.$form->Name.'</option>';
    }
}
return $str.'</select>';

Example: Embed Form Snippet

This example shows you how to gather the required information to embed a Wufoo form on your site programmatically using the Forms API. Let’s walk through this code now:

The lines below call the Forms API to get the form hash. If you already know the form hash, you can skip the first four lines of this code.

$curl = new WufooCurl();
$response = $curl->getAuthenticated('http://fishbowl.wufoo.com/api/v3/forms/web-hook-example.json', self::API_KEY);
$response = json_decode($response);
$hash = $response->Forms[0]->Hash;
echo $this->getFormSnippet($hash, self::SUBDOMAIN);

The last line of code above calls getFormSnippet and adds the $hash and $subdomain parameters to the Embed Form Code Snippet. When this call is echoed on the page, the javascript is executed and your form is printed to the screen.

return '<script type="text/javascript">var host = (("https:" == document.location.protocol) ? "https://secure." : "http://");document.write(unescape("%3Cscript src=\'" + host + "wufoo.com/scripts/embed/form.js\' type=\'text/javascript\'%3E%3C/script%3E"));</script>

<script type="text/javascript">
var '.$hash.' = new WufooForm();
'.$hash.'.initialize({
\'userName\':\''.$subdomain.'\', 
\'formHash\':\''.$hash.'\', 
\'autoResize\':true,
\'height\':\'416\', 
\'ssl\':true});
'.$hash.'.display();
</script>';

Example: Submit a Form

Sometimes you must host your Wufoo form on your own site by embedding the XHTML/CSS code. For example, if you’re hosting the form on your high-traffic home page or you want to write custom javascript to handle some special case, you’ll have to embed the code on your without the iFrame. This is easy enough, but you’ll need a way to submit the form values back to Wufoo.

For the following example, we’ll show you what it will take to create the same directory structure as the the code sample provided.

Your first step is to download the XHTML/CSS code for your form. In our example, we’ve downloaded a sample XHTML/CSS file to the api-submit-examples directory. You’ll have to edit this file to point to your code snippet php page. For example, given the following directory structure on your web server:

/examples/
- ApiExamples.php
- index.php
/examples/api-submit-example
- /css/
- /images/
- /index.html
- /scripts/

you’d edit your index.html, setting the form’s action atribute to point to the to the index.php file, as shown below.

<form action="../index.php?functionName=submitForm" id="form7" name="form7" class="wufoo topLabel page" autocomplete="off" enctype="multipart/form-data" method="post" >

At the root of examples you’ll find the index.php file you pointed to when you changed your form’s action attribute and a ApiExamples.php file. The index.php file contains the following code, which simply boostraps the ApiExample class.

require_once('ApiExamples.php');
$example = new ApiExample();
$functionName = $_GET['functionName'];
$example->$functionName();

With this structure in place, the form’s action attribute will submit the form values to /examples/index.php which will instantiate the ApiExample class and call the submitForm function, which we’ll review below.

The goal of this function is to get the form values into an array which we can pass to the postAuthenticated function of the WufooCurl object, which expects the post parameters to be in $name/$value pairs. If the posted value is a file, the “@” character must be appended to the file path. To further complicate things, we need to move the files to a randomly named temp directory that you control, then delete the files before the request terminates. If we did not create this temp directory, your user’s files would have a random file name matching the $FILE’s temp_name rather than the file name the user specified. If we did not delete the temp directories, these useless files would pile up on your server. To read further into this matter, check out the PHP documentation related to file uploads.

Armed with this knowledge, let’s dig into the steps required.

First, we loop over the $_POST array, creating our own temporary one.

foreach ($_POST as $key => $value) {
    $params[$key] = $value;
}

Next, we create a random directory on our server where we’ll store the uploaded files.

$dir = '/Users/tssabat/Desktop/upload/'.mt_rand(0, 100000).'/';
mkdir($dir);

Then we perform the move and fill an array named delete with the files we move from the temp $FILES directory to the one we created above. We give these files the user-specified file name rather than the random name given by PHP. Along the way, we also add the file path to our $params array, prepending the “@” sign to signify that they are file paths rather than text values.

foreach ($_FILES as $key => $value) {
    $path = $dir.str_replace('/','', str_replace('..', '', $_FILES[$key]['name']));
    move_uploaded_file($_FILES[$key]['tmp_name'], $path);
    $params[$key] = '@'.$path;
    $delete[] = $path;
}

Note that when we create the $path variable, we strip out malicious characters like “..” and “/” from the user-defined file name. This prevents a hacker from uploading arbitrary files to Wufoo or deleting files on your server. Typically Apache runs with limited permissions and you’d have to grant read/write permissions to the $dir created above, but we leave this code in place to plan for the worst-case scenario where your server is running with root permissions, which is a BAD THING.

Next, we create the WufooCurl object and call the post function on it, passing the $params array we created above.

try {
    $curl = new WufooCurl();
    $response = $curl->post(
        $params,
        'https://fishbowl.wufoo.com/api/v3/forms/api-submit-example/entries.json', 
        self::API_KEY);
} catch (Exception $e) {
    print_r($e);
}

Finally, we delete the files and $dir to keep them from piling up on your server.

foreach ($delete as $file) {
    unlink($file);
}
rmdir($dir);

And that’s about it. A bit complicated, but hopefully you’ve got it.

The WufooCurl object

The WufooCurl object does most of the heavy lifting for you in this project. Since we reference it often, let’s go over the details of it before we get started.

Public Methods

The WufooCurl object has a handful of public methods that we’ll familiarize ourselves with now.

The getAuthenticated function

This is the function you’ll use when making GET calls against the Wufoo API. Almost all of the resources in Wufoo have a GET call, so this this is the one you’ll probably use most often. This function takes two arguments, the $url and $apiKey variables, which are outlined below:

$url - is the full URL to the resource you’re trying to reach, including the query string arguments. An example of a URL is http://fishbowl.wufoo.com/api/v3/users.xml?pretty=true.

$apiKey

The postAuthenticated function

This is the function you’ll use when making POST calls against the Wufoo API. It has the same to arguments as getAuthenticated and adds one more, which is described below:

$postParams - is an associative array (key and values are important) which contains the values you wish to post. For example, when posting to submit a form, the following associative array would be appropriate.

array(
    'Field1' => 'Some value',
    'Field2' => 'Another One'
);

So it’s simple, you’ll load the $postParams with the values you want to send, and the CurlService class will take care of the rest.

Under The Covers

You could get by working with just the public methods, but to get a better idea of what’s going on behind-the-scenes, let’s take a look at the structure of the calls and some of the private methods as well.

As the name suggests, we’re working with PHP’s implementation of cURL, the world’s formost URL fetcher. To set up cURL for each call, we’ll initiliaze the cURL reference, like so:

$this->curl = curl_init($url); 

With your cURL reference, you set some basic options calling setBasicCurlOptions, the details of which follow:

private function setBasicCurlOptions() {
    //http://bugs.php.net/bug.php?id=47030
    curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($this->curl, CURLOPT_USERAGENT, 'Wufoo API Wrapper');
    curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
}

In this case, just trust us that you need to set these. If you want to read further, you an check out the [curl_setopt](http://php.net/manual/en/function.curl-setopt.php "curl_setopt Documentation") documentation.

From there, each call makes a few more adjustments. For example, the post call sets these options:

curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Content-type: multipart/form-data', 'Expect:'));
curl_setopt($this->curl, CURLOPT_POST, true);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $postParams);      
if ($apiKey) curl_setopt($this->curl, CURLOPT_USERPWD, $apiKey.':footastical');

CURLOPT_HTTPHEADER - We set this array to multipart/form-data to signify that we may be sending along files. The Expect: value overrides cURL’s default value of Expect:100, which will cause this code to choke.

CURLOPT_POST - Tells the server to expect POST parameters.

CURLOPT_POSTFIELDS - Is associative array we pass in which we want to make to the server as POST parameters.

CURLOPT_USERPWD - is how cURL expects username and password to be sent to the server. Basic authentication expects the format {username}:{password}. Since we’re only passing in the API key, we’ll send the api key along and use a placeholder (footastical) for the password.

Next, we tell the server to make the call

$response = curl_exec($this->curl);

From there, three more calls are made, which you can look at if you like. Here’s a quick summary of what they do:

setResultCodes - grabs the HTTP status code from the response.

checkForCurlErrors - checks that the basic call worked.

checkForPostErrors lets 200 (ok) or 201 (created) status codes go through and throws an exception for all other http codes.

checkForGetErrors lets 200 (ok) status codes go through and throws an exception for all other http codes.

And finally we close the curl connection and return the response.

curl_close($this->curl);
return $response;

When you instantiate the the WufooCurl class in your own code, remember to wrap all methods called from it in a try catch block to catch the thrown exceptions.

Updated : December 1st, 2010