/SmartyStreetsAPI

API Service for SmartyStreets

Primary LanguagePHPGNU General Public License v3.0GPL-3.0

Build Status: Build Status Powered by PHP Released under the GPL-3 License

Table of Contents

WSI-Services SmartyStreetsAPI

PHP library for parsing and validating street addresses against SmartyStreets API. An API ID and Token from SmartyStreets is required to utilize this library. You can create a SmartyStreets account & obtain an API key by creating an account, then generate a Secret key.

About SmartyStreets

SmartyStreets

SmartyStreets provides address geocode parsing & verification, city, state, zip matching, address auto-complete, and address extraction. Free and commercial accounts are available.

Address validation offers many benefits - less returned mail, better address data, consolidated duplicate addresses, improved communication with customers, reduced mailing costs, less time dealing with bad data, and increased delivery speeds. SmartyStreets gives you all of that, and then some.

Installing SmartyStreetsAPI

GIT

Clone the GIT repository locally:

$ git clone https://github.com/WSI-Services/SmartyStreetsAPI.git

Composer

Add the library to your Composer dependencies from the command line:

$ composer require wsiservices/smartystreetsapi

OR

Add the required section to your composer.json file:

"require": {
	"wsiservices/smartystreetsapi": "1.*"
}

Dependencies

Install system dependencies:

apt-get -y install php5-dev libcurl3 libmagic1 zlib1g-dev

Install PECL dependency 'raphf':

pecl install raphf

Create PECL 'raphf' configuration file: /etc/php5/mods-available/raphf.ini

; configuration for php raphf module
; priority=20
extension=raphf.so

Enable PHP module 'raphf':

php5enmod raphf

Install PECL dependency 'propro':

pecl install propro

Create PECL 'propro' configuration file: /etc/php5/mods-available/propro.ini

; configuration for php propro module
; priority=30
extension=propro.so

Enable PHP module 'propro':

php5enmod propro

To locate the installed library paths, replace {LIBRARY} with libz,

libcurl, libevent.*, & libidn:

ldconfig -p | grep "{LIBRARY}.so" | awk '{print $4}' | head -n1

Install PECL dependency 'pecl_http':

pecl install pecl_http

Answer the following questions with the library paths found:

where to find zlib [/usr] :
where to find libcurl [/usr] :
where to find libevent [/usr] :
where to find libidn [/usr] :

Create PECL 'http' configuration file: /etc/php5/mods-available/http.ini

; configuration for php http module
; priority=40
extension=http.so

Enable PHP module 'http':

php5enmod http

Initialize composer for development:

composer install

Initialize composer for production:

composer install --no-dev --optimize-autoloader

Using SmartyStreetsAPI

Framework Support

Laravel

SmartyStreetsAPI provides a service provider and facade for Laravel.

Register the service provider in the providers array, located in config/app.php:

'providers' => [
	// ...

	WSIServices\SmartyStreetsAPI\Support\Laravel\Facade::class,
]

Add an alias within the aliases array found in config/app.php:

'aliases' => [
	// ...

	'SmartyStreetsAPI'	=> WSIServices\SmartyStreetsAPI\Support\Laravel\ServiceProvider::class,
]

Publish the configuration file:

php artisan vendor:publish

Edit the configurations, located in config/smartystreetsapi.php:

return [

	'authentication' => [
		'secret' => [
			'auth-id'		=> '',
			'auth-token'	=> ''
		],
		'website' => [
			'auth-id'		=> ''
		]
	],

	...

	'request-class' => SmartyStreetsAPI\Request\cURL::class,

	...
];

Provide the authentication values from SmartyStreets, and set your chosen request class.

Namespace

use WSIServices\SmartyStreetsAPI;

Class: Configuration

$configuration = new Configuration($configArray);

Class: Factory

$factory = new Factory(new Log);

$factory->setConfiguration($configuration);

Class: Service

$service = $factory->getService('us-street-address');

$service->getRequest($optionsArray);

The following service types are provided with the corresponding classes:

us-street-address
\WSIServices\SmartyStreetsAPI\Service\UsStreetAddress
us-zip-code
\WSIServices\SmartyStreetsAPI\Service\UsZipCode
us-autocomplete
\WSIServices\SmartyStreetsAPI\Service\UsAutocomplete
us-extract
\WSIServices\SmartyStreetsAPI\Service\UsExtract
international-addresses
\WSIServices\SmartyStreetsAPI\Service\InternationalAddresses
download
\WSIServices\SmartyStreetsAPI\Service\Download
** NOTE: Currently only *us-street-address* has been completed.**

US Street Address Service

This service has two methods for modifying the request:

$service->XStandardizeOnly();

$service->XIncludeInvalid();

Download Service

This service has multiple asset paths, which should be set in the options array:

us-street-api
/us-street-api/linux-amd64/latest.tar.gz
us-street-data
/us-street-api/data/latest.tar.gz
us-zipcode-api
/us-zipcode-api/linux-amd64/latest.tar.gz
us-zipcode-data
/us-zipcode-api/data/latest.tar.gz
us-autocomplete-api
/us-autocomplete-api/linux-amd64/latest.tar.gz
us-autocomplete-data
/us-autocomplete-api/data/latest.tar.gz

Class: Request

Their are four request type classes to choose from. Two types are native to PHP (ie: file_get_contents & curl), which don't have any additional dependencies. The other two types (ie: pecl_http2 & GuzzleHttp) require installing either a PECL PHP module or Composer package.

Utilities

This library includes utilities for documentation and testing.

phpUnit

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.

From the root of the project, run the following command:

$ ./utilities/phpunit.sh

Example Output:

PHPUnit 4.8.22-1-g1ae3a68 by Sebastian Bergmann and contributors.

................................................................. 65 / 97 ( 67%)
................................

Time: 44.39 seconds, Memory: 8.50Mb

OK (97 tests, 135 assertions)

Generating code coverage report in Clover XML format ... done

Generating code coverage report in HTML format ... done

phploc

A tool for quickly measuring the size and analyzing the structure of a PHP project.

From the root of the project, run the following command:

$ ./utilities/phploc.sh

Example Output:

phploc 3.0.0-1-gdf11fc5 by Sebastian Bergmann.

Directories                                          9
Files                                               35

Size
  Lines of Code (LOC)                             4943
  Comment Lines of Code (CLOC)                    1191 (24.09%)
  Non-Comment Lines of Code (NCLOC)               3752 (75.91%)
  Logical Lines of Code (LLOC)                     791 (16.00%)
    Classes                                        216 (27.31%)
      Average Class Length                           6
        Minimum Class Length                         0
        Maximum Class Length                        23
      Average Method Length                          2
        Minimum Method Length                        0
        Maximum Method Length                       12
    Functions                                      487 (61.57%)
      Average Function Length                       97
    Not in classes or functions                     88 (11.13%)

Cyclomatic Complexity
  Average Complexity per LLOC                     0.07
  Average Complexity per Class                    2.57
    Minimum Class Complexity                      1.00
    Maximum Class Complexity                     24.00
  Average Complexity per Method                   1.93
    Minimum Method Complexity                     1.00
    Maximum Method Complexity                    21.00

Dependencies
  Global Accesses                                    0
    Global Constants                                 0 (0.00%)
    Global Variables                                 0 (0.00%)
    Super-Global Variables                           0 (0.00%)
  Attribute Accesses                               400
    Non-Static                                     400 (100.00%)
    Static                                           0 (0.00%)
  Method Calls                                     719
    Non-Static                                     694 (96.52%)
    Static                                          25 (3.48%)

Structure
  Namespaces                                        10
  Interfaces                                         2
  Traits                                             0
  Classes                                           20
    Abstract Classes                                 2 (10.00%)
    Concrete Classes                                18 (90.00%)
  Methods                                           83
    Scope
      Non-Static Methods                            82 (98.80%)
      Static Methods                                 1 (1.20%)
    Visibility
      Public Methods                                81 (97.59%)
      Non-Public Methods                             2 (2.41%)
  Functions                                          5
    Named Functions                                  2 (40.00%)
    Anonymous Functions                              3 (60.00%)
  Constants                                          3
    Global Constants                                 0 (0.00%)
    Class Constants                                  3 (100.00%)

Tests
  Classes                                           13
  Methods                                           96

phpDocumentor

A tool that makes it possible to generate documentation directly from your PHP source code.

From the root of the project, run the following command:

$ ./utilities/phpdoc.sh

Example Output:

The documentation for this library is generated in the documentation/api directory.

Code Coverage

Running phpUnit generates logs in directory tests/logs. Below you can see the files and descriptions of the generated output.

coverage.txt
The TEXT format for code coverage information logging produced by PHPUnit, loosely based upon the one used by Clover.
coverage.xml
The XML format for code coverage information logging produced by PHPUnit, loosely based upon the one used by Clover.
report (directory)
The HTML format for code coverage information; provides a package overview, namespace & class descriptions, charts, and reports (including errors, markers, and deprecated elements).
testdox.txt
The TEXT format of the PHPUnit TestDox, to generate agile project documentation based on the tests.
testdox.html
The HTML format of the PHPUnit TestDox, to generate agile project documentation based on the tests.
logfile.tap
The Test Anything Protocol (TAP) is Perl's simple text-based interface between testing modules.
logfile.json
The JavaScript Object Notation (JSON) is a lightweight data-interchange format.

You can find more out about phpUnit logging in their documentation Chapter 14. Logging and Chapter 15. Other Uses for Tests.

SmartyStreets Notes

Status Codes and Results

  • Responses will have a status header with a numeric value.
  • This value is what you should check for when writing code to parse the response.
  • The only response body that should be read and parsed is a 200 response.

US Street Address API

Scheme:
https
Required; non-secure http requests are not supported.
Hostname:
api.smartystreets.com
Path:
/street-address
Query String:
?auth-id=123&auth-token=abc
Authentication information, inputs, etc. Additional query string parameters are introduced in the next section.
Methods:
GET, POST

Code / Response and Explanation

200 - OK:
Success! A JSON array containing zero or more address matches for the input provided with the request. If none of the submitted addresses validate, the array will be empty ([]). The structure of the response is the same for both GET and POST requests.
400 - Bad Request:
(Malformed Payload) A GET request lacked a street field or the request body of a POST request contained malformed JSON.
401 - Unauthorized:
The credentials were provided incorrectly or did not match any existing, active credentials.
402 - Payment Required:
There is no active subscription for the account associated with the credentials submitted with the request.

US ZIP Code API

Scheme:
https
Required; non-secure http requests are not supported.
Hostname:
api.smartystreets.com
Path:
/zipcode
Query String:
?auth-id=123&auth-token=abc
Authentication information, inputs, etc. Additional query string parameters are introduced in the next section.
Methods:
GET, POST

Code / Response and Explanation

200 - OK:
Success! The response body will be a JSON array containing zero or more matches for the input provided with the request. The structure of the response is the same for both GET and POST requests.
400 - Bad Request:
(Malformed Payload) The request body of a POST request contained no lookups or contained malformed JSON.
401 - Unauthorized:
The credentials were provided incorrectly or did not match any existing, active credentials.
402 - Payment Required:
There is no active subscription for the account associated with the credentials submitted with the request.

US Autocomplete API

Scheme:
https
Required; non-secure http requests are not supported.
Hostname:
autocomplete-api.smartystreets.com
Path:
/suggest
Query String:
?auth-id=123&auth-token=abc
Authentication information, inputs, etc. Additional query string parameters are introduced in the next section.
Methods:
GET

Code / Response and Explanation

200 - OK:
Success! The response body is a JSON object with a suggestions array containing suggestions based on the supplied input parameters.
400 - Bad Request:
(Malformed Payload) The request was malformed in some way and could not be parsed.
401 - Unauthorized:
The credentials were provided incorrectly or did not match any existing, active credentials.
402 - Payment Required:
There is no active subscription for the account associated with the credentials submitted with the request.

US Extract API

Scheme:
https
(Required; non-secure http requests are not supported.
Hostname:
extract-beta.api.smartystreets.com
Path:
/
Query String:
?auth-id=123&auth-token=abc
Authentication information, inputs, etc. Additional query string parameters are introduced in the next section.
Methods:
POST

Code / Response and Explanation

200 - OK:
Success! The response body is a JSON object containing meta-data about the results and zero or more extracted addresses from the input provided with the request. See the annotated example below for details.
400 - Bad Request:
(Malformed Payload) The request body was blank or otherwise malformed.
401 - Unauthorized:
The credentials were provided incorrectly or did not match any existing, active credentials.
402 - Payment Required:
There is no active subscription for the account associated with the credentials submitted with the request.
413 - Request Entity Too Large:
The request body was larger than 64 Kilobytes.

Verify International Addresses

Scheme:
https
Required; non-secure http requests are not supported.
Hostname:
international-street.api.smartystreets.com
Path:
/verify
Query String:
?auth-id=123&auth-token=abc
(Additional query string parameters are required; consult the next section.
Methods:
GET

Code / Response and Explanation

200 - OK:
Success! A JSON array containing zero or more address matches for the input provided with the request. If none of the submitted addresses validate, the array will be empty ([]).
400 - Bad Request:
(Malformed Payload) Inputs from the request could not be interpreted.
401 - Unauthorized:
The credentials were provided incorrectly or did not match any existing, active credentials.
402 - Payment Required:
There is no active subscription for the account associated with the credentials submitted with the request.
403 - Forbidden:
Because the international service is currently in a limited release phase, only approved accounts may access the service. Please contact us for your account to be granted access.
422 - Un-processable Entity:
A GET request lacked required fields.
429 - Too Many Requests:
Too many requests with exactly the same input values were submitted within too short a period. This status code conveys that the input was not processed in order to prevent runaway charges caused by such conditionas as a misbehaving (infinite) loop sending the same record over and over to the API. You're welcome.
504 - Gateway Timeout:
Our own upstream data provider did not respond in a timely fashion and the request failed. A serious, yet rare occurence indeed.

Download API

Scheme:
https
Required; non-secure http requests are not supported.
Hostname:
download.api.smartystreets.com
Path:
/{$pack-path}
See the package listing for exact values.
Query String:
?auth-id=123&auth-token=abc
Authentication information, inputs, etc. Additional query string parameters are introduced in the next section.
Methods:
GET

Code / Response and Explanation

307 - Temporary Redirect:
Success! The Location response header will contain the actual download URL. This link will only last for a few seconds so it will be necessary for you to follow that redirect immediately. Passing the -L flag to the curl command (as shown in the examples on this page) will accomplish this automatically.
401 - Unauthorized:
The credentials were provided incorrectly or did not match any existing, active credentials.
402 - Payment Required:
There is no active enterprise subscription for the account associated with the credentials submitted with the request.
404 - Not Found:
The package you requested does not exist as specified. See the package listing for exact URL path values.
405 - Method Not Allowed:
Request method used is not allowed. See allowed request methods.

Package Listing

Each package will include a text file with installation instructions and documentation.

Package - Token / URL Path (insert in request URL)

US Street Address API
us-street-api
us-street-api/linux-amd64/latest.tar.gz
US Street Address Data
us-street-data
us-street-api/data/latest.tar.gz
US ZIP Code API
us-zipcode-api
us-zipcode-api/linux-amd64/latest.tar.gz
US ZIP Code Data
us-zipcode-data
us-zipcode-api/data/latest.tar.gz
US Autocomplete API
us-autocomplete-api
us-autocomplete-api/linux-amd64/latest.tar.gz
US Autocomplete Data
us-autocomplete-data
us-autocomplete-api/data/latest.tar.gz