API Conventions

APIs are about standards. We've worked hard to establish some sensible conventions in forming our API; some are industry standards, many are inspired by our favorite APIs.

Understand these common conventions in the Kiva API and making sense of the rest should be a breeze.

RESTful

First and foremost, the Kiva API is a web-service API. It works like the web (e.g., HTTP) and works well with the tools of the web (e.g., browsers). More specifically, the Kiva API is a RESTful web-service API. To us, “REST” means that our API is resource-oriented where the method calls are actually URLs that point to data you fetch or modify. The “ful” part of this means we not that picky about a formal definition of REST and actually quite happy to use our intuition about things as we go along.

At Kiva, our resources are generally the nouns you think of when visit our site – Loans, Lenders, Field Partners, and Lending Teams. Thus, in true RESTful fashion, if you wanted to fetch data about a loan at Kiva, you'd make an HTTP GET request accompanied by the proper URI for the loan about which you want information. To create a loan, you might send a POST request to a similar URI. Since the Kiva API currently only supports fetching data, you only need to concern yourself with GET requests for now.

Generally, the RESTful nature of an API is wrapped up on the manner in which that API lets users modify, remove, or fetch data. However, it has some healthy implications for how other very important parts of the API work too.

Response Formats

If you make a Kiva API call, you're guaranteed some kind of response. If you make a successful call you'll get an HTTP response with a status 200 OK and the content of that response will usually be data, serialized in some meaningful way.

You can request response data from any Kiva API call in one of two formats, JSON or XML. (Some calls are available in feed-based formats, which we talk about later.) The format depends on which extension you append to the end of your URL request. This call returns the newest loans at Kiva as JSON:

http://api.kivaws.org/v1/loans/newest.json

This call returns the same data as XML:

http://api.kivaws.org/v1/loans/newest.xml

Simple. The format you choose probably depends on what you're most familiar with and what tools you have available to you. If you can't decide, we suggest JSON because it's concise, predictable, and all-around awesome. Some would say it is beautiful. We won't hide the fact that it is our favorite of the two. In fact, most of our data responses are designed for JSON first, then translated to XML systematically.

Because XML is by definition, extensible, it also means that saying we support XML responses doesn't provide much detail how the data might be structured. Really useful XML documents often conform to a more specific standard tied to the data they represent. In choosing our convention for XML, our first goal was to make it intuitive, and the second was to make it easily de-serializable. That is, we wanted to make the data easy to organize into an in-memory data structure such as a PHP array or a hash in Ruby. The JSON format already has this property so we created a few rules to help translate hierarchical data into XML reliably.

  • Data responses are made up of ordered arrays, associative arrays (hashes), and strings.
  • The root of the data response is always an associative array.
  • Associative arrays are composed of keys and values. Keys translate to XML elements where the name of the key is the name of the element. The value of the element can be a string or another element depending on value type.
  • Associative arrays themselves are elements with keys as child elements. The array takes its name from the respective key from the parent array. The root array always takes the name response.
  • Ordered arrays also translate to named elements, but their child elements are different. The children take their name from the singular version of the parent (eg, “loans” becomes “loan”). Also, the parent element representing the array has an attribute type with the value of “list.”

As an example, here's a simplified API response in JSON:

{ "people": [ {"name":"Jeremy","id":2}, {"name":"Roma","id":38}, {"name":"Zvi","id":21} ] }

And here's how this same data translates to XML:

<response> <people type="list"> <person><name>Jeremy</name><id>2</id></person> <person><name>Roma</name><id>38</id></person> <person><name>Zvi</name><id>21</id></person> </people> </response>

Test Responses

We haven't told the full story yet. Actually, we've baked in a very special response format to every API call that we think will be really helpful for testing the Kiva API or debugging programs built on the API. Since our API is RESTful, it is trivial to call from a web browser, but JSON and XML are designed for computers to read, not humans. We thought it would be handy to provide an HTML response format that makes it easy for humans to play around with the API using any common browser. To try this out, click on this link:

http://api.kivaws.org/v1/loans/newest.html

Voila! We simply subbed out our old response extension for an HTML extension. In fact, this also works if you don't provide an extension at all. Compare this to what happens in your browser if try to request a JSON response instead.

Responses as Feeds

Some API calls can also return responses formatted as a syndicated feed, such as RSS. These are really useful with many consumer tools which have powerful built-in capabilities for tracking, presenting, and mashing up feeds. Since working with feeds can be very different than working with standard API responses, feeds have their own section. Just note that if you request a feed format for an API method which doesn't support it, you'll get an error.

JSONP

JSONP is an unofficial protocol that allows scripts to work around the "same origin policy", permitting client-side scripts to easily access JSON data originating on a different server. There are some risks, and generally we encourage developers to retrieve and verify JSON on the server side. However, due to significant demand, we've decided to add JSONP support as well. If you add a "jsonp= ... " parameter to any .json request, the JSON will come back wrapped in a function call to the callback you've specified.

As an example, the simplified API response above, if requested with a "jsonp=my_js_function" GET parameter, would come back as follows:

my_js_function({ "people": [ {"name":"Jeremy","id":2}, {"name":"Roma","id":38}, {"name":"Zvi","id":21} ] })

As this is now javascript rather than pure JSON, the "Content-type" header of the API response will be "text/javascript" rather than "application/json".

Errors

Like any good RESTful service, your first clue to how your API request went is the HTTP status code. If it's something other than 200 OK, something went awry. While some such responses might be informational (300s), most will be errors, either yours (400s) or ours (500s).

Here are some common HTTP error codes you might see in your responses:

400 Bad Request
Something was wrong with your request. More than likely, you passed in a bad parameter value.
401 Unauthorized
The request you made requires authorization yet no credentials were provided. Likely, you forgot an Authorization header for a resource that requires it.
403 Forbidden
Your request was understood by the server and rejected it. This is common when you request sensitive resources insecurely (eg, not using HTTPS to access user-sensitive data), or if your authorization credentials don’t match up with data your are trying to access - for example you supply Lender credentials to access private data for a Partner.
404 Not Found
We couldn't find the resource you requested. In other words, your URI was probably incorrect. It may be the case of a non-existent resource name or a bad ID parameter.
405 Method Not Allowed
The resource you requested is valid, but it doesn't support the HTTP method you used to access it. For example, you may have sent a POST request for a resource only available by a GET request.
500 Internal Server Error
This one's our fault. Kindly post to the forum if you see this so we can look into it.
503 Service Unavailable
The Kiva servers are overloaded or down for maintenance. In the latter case, we'll typically add a Retry-After header that lets you know when things might be back up.

HTTP status codes are good for web tools, but fancy software programs and humans deserve more. That's why every error response will also have a simple content body with more detail on your error. We provide a computer-friendly code and a human-friendly message both serialized in the response format you specified. If you made a GET request for this URI:

http://api.kivaws.org/v1/gobbledygook.json

here's what you'd get:

{ "code":"org.kiva.InvalidResource" "message":"We could’t find the resource you were trying to access. Check your URL to confirm it’s a valid API endpoint. Check your HTTP request method (GET, POST, etc.) to make sure it is supported by the corresponding endpoint." }

XML responses look similar with a root element of error. Test responses in HTML will also show you the HTTP status code in the HTML response. Errors for a feed format (RSS, ATOM, etc.) will default to HTML output.

The message value in errors is our attempt to help you resolve the problem with your call. For instance, if you pass in a bad parameter, we'll tell you which parameter didn't make the cut. The code value is a unique string in reverse-domain notation that your application can test against to get finer granularity on what happened outside of the HTTP status. You may choose to use this code to pass on a localized error message to your users in certain conditions. Here's a list of some of the more common codes:

org.kiva.InvalidResource
The URI in your request was malformed so we don't know what resources you're looking for. Perhaps the API endpoint you want to call doesn't exist or you might have a poorly formed parameter in the URI that is causing problems.
org.kiva.MalformedParameter
You passed in a value that was outside the bounds of what we allow for a particular parameter.
org.kiva.InvalidIdentifier
You passed in an value for a identifier parameter that does not correspond to anything we know about. For example, '111' is not a valid ID for a loan.
org.kiva.HttpsRequired
You are trying to use HTTP to access a resource that is only available via HTTPS.
org.kiva.ServerMaintenance
We're upgrading our servers to make Kiva better and the Kiva API is not available at this time. Try again later.

Parameters

In a RESTful API, parameters are a bit of a misnomer since the focus is usually on the unique URI you send with your HTTP request. Still, most developers think in terms of functional API calls so we think it helps to talk a bit about what parameters look like in our system.

The most important distinction is between required and optional parameters. You can't make an API request without a required parameter, and there is no such thing as a default value for something that's required. Because they are so essential and distinctive, required parameters always tend to pop up in the middle of our API URIs rather than somewhere at the end (i.e., the query string). For example, check out this call for detail about a loan:

http://api.kivaws.org/v1/loan/76950.xml

This request looks like a simple URL, but we call this API method loan/<id> because the value 76950 is actually a required parameter. If you changed the value to 76961 it is intuitive that you'd get data back for a different loan, which is part of the beauty of the API being RESTful.

Optional parameters usually come in the query string of the HTTP request. Sometimes they have default values too. Check out these API calls:

http://api.kivaws.org/v1/search.json http://api.kivaws.org/v1/search.json?page=1

These two calls return the same data because page is an optional parameter that has a default value of 1. Since it is passed in the query string and not a part of the main URI, it's also pretty intuitive that you don't need it for a call.

All parameters to Kiva API calls are validated. We do this mainly to protect you from making mistakes. We'd hate it if you felt responsible for accidentally screwing things up here at Kiva, but more importantly we want to give you the right feedback so you know how to fix your request. When you pass bad parameter values to an API call, we'll let you know with an error response.

Any parameter might have a unique set of restrictions, but there are some common types we refer to in our documentation:

boolean
an integer value, 0 or 1
integer
an signed integer value, 0 or 1
number
any number, including signed floats
string
almost everything else
array
a comma-delimited list of any of the above

The most significant of these basic types is the array since it's able to include values of other types. Arrays are powerful in that they let you easily make requests for lots of different data, or different types of data at once. Whitespace is respected both before and after the comma delimiter when parsing values in an array. It's okay to have an array parameter with only one value (i.e., no commas), but arrays cannot contain other arrays. Here's an example of an API call that accepts an array value:

http://api.kivaws.org/v1/loans/76950,277,37541.xml

This is call is just like one of our earlier examples except that instead of fetching the data for just one loan, we can fetch the data for three.

app_id

Every method call can accommodate app_id as a parameter. This is a value that uniquely identifies your application apart from others calling the API. It is only used for tracking purposes. You're free to send any valid value you wish.

If sent, an App ID must be a string in reverse-DNS notation at least 8 characters in length. Only alphanumeric characters, dashes, and dots are allowed. (A-Z a-z 0-9 '.' '-') Unicode and high-ASCII characters are not recommended as they are not reliably supported in URIs. If you send an invalid App ID in your API request, you may receive an error response.

We suggest you use a reversed-DNS prefix you own (like org.kiva) to ensure uniqueness of your ID. Using someone else's App ID is pointless, other than inflating someone else's statistics. We don't use App IDs for rate-limiting or security. Examples of App IDs in the suggested format include:

org.kiva.build com.foo.myGreatApplication

In addition to including app_id in API calls, you can use them in referral links to the Kiva website. This helps us track which applications are sending traffic to Kiva and driving other actions, like lending or joining teams. Check out some examples here

Paging

If not for paging, most responses from the Kiva API would be unreasonably large for sending to thousands of requesters every hour. For example, there are over 80,000 loans at Kiva and nearly half a million lenders — each of these data sets are easily several megabytes large. Moreover, most applications can only use or represent a fraction of the data at a time anyway. Paging the data responses helps keep data exchange sane both for Kiva and applications.

We chose a simple model for data paging where page sizes are fixed for any one particular type of data. For example, loan listings currently come 20 to a page; lender listings are offered 50 to a page. Applications should not expect the page size for anyone type of data to stay constant forever, but we also don't plan to change a page size unless we come across a really good reason to do so. Since page sizes are fixed, you only have to supply a page number to pick a cross-section out of a large data response. The default page number for any applicable API method is always 1. For example if you request the list of newest loans suppling no parameters, you'll get paging information in your response that looks something like this (sans comments):

"paging": { "page": 1 // the current page represented "total": 105 // the total number of loan listings for this call "page_size": 20 // the number of listings returned per page "pages": 6 // the total number of pages available }

To get the full list of fundraising loans in this case, you'd need to call the same API method 5 more times with each of the page numbers 2 through 6. Currently, calling the method with page number 7 would return no results.

OAuth

Authorization

Kiva uses OAuth 1.0a protocol to control application access to protected resources. OAuth is an industry standard that allows a user to authorize an application to act on their behalf with certain permissions. OAuth gives the user a great deal of control and security in that the application never has full access to their account, passwords, or other credentials and that the user can revoke the application's access to their account any time using their Kiva account preferences.

The mechanics of OAuth 1.0a are fairly simple:

  1. Decide what kind of API access your application needs (e.g. Read-only access for a lender account).
  2. Request a Request Token.
  3. Redirect the user to Kiva with the Request Token, requesting particular scope of permissions.
  4. Kiva will handle authenticating the user on Kiva.org and will confirm the access request by your application with the user.
  5. If the user approves this request, Kiva will redirect the user back to your application along with a code you can use to confirm the approval. In most cases, your application will exchange this code directly through Kiva for a long-lived Access Token you can use for API access.
  6. Your application can then make requests for protected resources via the Kiva API until the access token expires or until the user revokes your application's access.

The wonderful people at the Internet Engineering Task Force produced this beautiful diagram to explain an OAuth authorization flow:

Obtaining Request Tokens

The first step of the authentication is to obtain a request token from the request token endpoint.

POST https://api.kivaws.org/oauth/request_token
WARNING: You will end up in the seventh circle OAuth Authorization Header Hell if you try to construct the header yourself. Use a library: http://code.google.com/p/oauth/

The library you use must conform to the OAuth 1.0a standard and send all the required parameters in the OAuth 1.0a specification:

This method must be called via HTTPS using the POST method with parameters passed in the HTTP request body. The request must contain an OAuth 1.0a authorization header. Note the oauth_callback parameter is the one you entered when you configured your app on the developer dashbaord

If your request is successful the server will respond with a JSON object with the following properties:

  • oauth_token - The token identifier.
  • oauth_token_secret - The token key. This key should be protected securely as with all user private data.
  • oauth_callback_confirmed - This will always be set and always be true.

Let's consider an example. A website, Lender Web, wants to authenticate a user with Kiva.org to access their lending history via the Kiva API. To start the process, Lender Web requests a request token from Kiva. The request token response will look something like:

oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&oauth_token_secret=26Lm-E.nZo-K0524BydRsmmv14Xk5QT5j.erCyZQh6&oauth_callback_confirmed=true

If your request is rejected you will be returned a standard OAuth 1.0a error response. Your request may be rejected for any number of reasons including:

  • Your Authorization header is incorrectly calculated, malformed, or corresponds to an invalid or restricted client.
  • Failure to use HTTPS for the request.
  • Missing or invalid parameters or any other errors in the construction of your POST request.

Choosing an Authorization Flow

Before digging deep into authentication mechanics it is important to first understand which type of user interaction flow is appropriate for the kind of application you are building. Typically, you'll be limited by the software or devices your application targets, but you may also make certain decisions based on the expectations or needs of your users. The flow you choose determines how your user is directed to Kiva.org to approve your app and how the user arrives back at your app to complete the authentication process.

The supported flows are:

  1. Browser Redirect: This flow is best for most web sites and browser-based applications as well as apps on devices where a modern browser is available, such as a smartphone, laptop, or desktop computer.
  2. Out of Band: This flow is best for software environments without a web browser or that restrict integration between web browsers and your application. Simple mobile devices, video game consoles, TVs and other connected devices may fall in this category. Additionally, some developers may find this flow simplest for users with limited exposure to technology.
  3. Embedded Browser: This is an alternative of the Browser Redirect flow for apps that prefer not to redirect a user outside of their application for authentication. To use this flow you must be able to embed a web browser view into your application.

Browser Redirect flow for Websites

Browser Redirect is the most natural flow for most websites to authenticate with Kiva. That's because this flow leverages the power of URL redirects supported by every web browser in existence. When your app is ready to authenticate the user you simply send the user to a URL on Kiva. You'll know authentication has completed when the user is directed back to your website via a specific callback URL you register with your application. You'll also receive an authentication code or an error code in the URL query string to let you know how the auth exchange turned out.

Lender Web then directs the user to Kiva, with the request token to Kiva using the URL:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb&response_type=code&oauth_callback=https%3A%2F%2Flenderweb.org%2Fkiva_oauth_callback&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

At this point the user is directed to log in to Kiva and approve Lender Web for read-only access to private data in their account. If the user approves the app Kiva redirects the user to Lender Web using a HTTP redirect (status 303) to the callback URL pre-registered by Lender Web:

https://lenderweb.org/kiva_oauth_callback?oauth_verifier=dk202zas&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

The Lender Web server can now make a quick check with the Kiva API to confirm the code *dk202zas* is valid and to claim an access token valid for API requests to fetch private user lending history. If the user had rejected the authorization request the user would have been redirect to Lender Web at the same endpoint, but with a different query string:

https://lenderweb.org/kiva_oauth_callback?error_code=access_denied&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

Note that in either case a state parameter is preserved across the redirects so that Lender Web track exactly which user session it is being authenticated.

Browser Redirect flow for Devices

The Browser Redirect flow is a also convenient flow for native apps that run on devices where a modern browser is present. This includes popular desktop operating systems like Mac OS X & Windows and modern mobile operating systems like iOS & Android. In this scenario, URL redirects are used just as the flow between websites. The key difference is the local operating system brokers the redirects between your application and the user's web browser (rather than redirects being handled internally by the browser itself). In this flow a custom URL scheme is registered with the local OS and is used lieu of HTTPS in the Callback URL — this way the browser knows to redirect control back to your application rather than to a website as before.

Let’s imagine an example using an app, Lender App, designed to run on iOS devices. Like Lender Web this app wants to access lending history for a user and thus needs read-only access to private Kiva user data. Lender App starts the process by asking the local operating system to open a web page in the local browser, Safari. On iOS 4, the code looks like this:

hNSString* launchUrl = @"https://www.kiva.org/oauth/authorize?client_id=org.lenderweb.app&response_type=code&oauth_callback=x-application-org-lenderweb-app-iphone%3Akiva_oauth_callback&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];

Just as with the website example, the user must log in to Kiva and approve the application for read-only access to private data in their account. If access is approved, the Kiva redirects the user to the provided redirect URI with a new authentication code:

hx-application-org-lenderweb-app-iphone:kiva_oauth_callback?oauth_verifier=dk202zas&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

Note the custom URL scheme in this redirect, *x-application-org-lenderweb-app-iphone*. Normally, the browser (Mobile Safari) would not know how to handle a URL redirect with this custom protocol but that Lender App pre-registered this custom protocol with iOS before directing the user to Kiva for authentication. It does this by making sure this scheme is listed as a valid URL Scheme in the *Info.plist* resource of the its application bundle. Additionally, the app implements a callback function (on its UIApplicationDelegate) to handle the incoming URL redirect from the browser:

h-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { // handle URL }

Lender App can then process the authentication code form the query string of the URL parameter to complete the authentication process as normal. (NOTE: In this case no the optional state parameter was not used since Lender App only supports operation by a single user.)

Out of Band

The Out of Band flow is simple means to authorize an application without relying on tight integration between your app and a the user's web browser. The user still must have access to Kiva via a web browser to complete the authorization but that browser may be on an entirely different device altogether. The application starts the process by directing the user to the OAuth authorization endpoint on Kiva along with its client ID. One option is for the application to open the URL in a local browser on the device, if available. Other options may include directing the user to visit a special website to start the process or sending the user an email or SMS with a link to begin the authorization process. Once the user is on Kiva, the user logs in and approves the app as normal, but rather than being programmatically redirected back to the application the user is presented with a short code that must be entered or pasted manually into the application. Because the authorization code must be transferred by the user outside of a consistent redirect flow we call this process "Out of Band." Despite the extra manual step of code entry, this flow may actually be easier or more intuitive for users who would otherwise be disoriented by URL redirects between different applications or websites.

For this flow we'll use the example of an application, Lender TV, designed to run on a smart TV without a dedicated web browser. Instead of directing the user to Kiva with a link or button, the app starts by instructing the user to visit a special website on a computer at home:

http://lenderweb.org/tv

TThis website is a simple page that informs the user the user will be redirected to Kiva in order to continue authorizing the Lender TV app to access their Kiva account. After a brief delay the user is redirected to the OAuth authorization endpoint using a special redirect URI, “oob”. The oauth_token is the request token you attained earlier:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb.app&response_type=code&oauth_callback=oob&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

This reserved URI, called an URN, is reserved for applications wanting to use the Out of Band (OOB) flow. It lets Kiva know not to redirect the user back to the app via the browser, but to display a human-readable authorization code directly to the user after authorization. Thus, once our user logs in to Kiva and approves the app the user is shown a short sequence of characters like so:

R6KPLW

The user then has a fixed amount of time, about 30 minutes, to enter the code in the Lender TV app running on their television. She enters the code using their remote, clicks confirm, and Lender TV proceeds to validate the code entered via the Kiva API. If all goes well Lender TV will be returned an access token suitable for making API requests for their account history.

Embedded Browser

The final authorization flow supported by Kiva is very similar to the Browser Redirect flow except that the user handles login and approval via a browser view embedded directly in the application. This flow is acceptable for both native apps that want to avoid redirecting the user’s attention outside to an external browser, and web apps for which a traditional HTTP redirect or opening a separate browser window would result in an undesirable user experience. This flow is more complicated than others and also requires special care to prevent a secure and consistent authorization flow on the Kiva website.

To explain this flow we'll user Lender App again, but this time using a different redirect URI. Lender App starts the authentication process but popping up a floating browser view on the user's screen which is already set to the OAuth authorization endpoint:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb.app&response_type=code&oauth_callback=x-application-org-lenderweb-app-iphone%3Akiva_oauth_redirect&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

At this point the user is presented with the Kiva login screen in the embedded browser view. She logs in and chooses to approve the application to access their private account data. Kiva performs an HTTP redirect as normal after the approval along with a new authorization code:

hx-application-org-lenderweb-app-iphone:kiva_oauth_callback?oauth_verifier=dk202zas&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app&state=6ED1279AB3340E9

Normally, the browser would automatically handle this redirect, but since Lender App has embedded this browser instance as an UIWebView it is also able to inspect and intercept any page load or redirects it sees fit using a UIWebViewDelegate. When it sees that the webview wants to load the special URL above it intercepts the request, processes the query string from the URL, detects and validates the authorization code with Kiva, then proceeds to close the embedded browser view and confirm the authorization process.

NOTE: For now embedded web views must use the same login and approval pages as for other flows. In the future we may provide options for optimizing the views for mobile devices and embedded web views.

Requesting Access

Regardless of the specific flow you choose for your application you need to redirect the user to the authorization page to start the authentication process:

https://www.kiva.org/oauth/authorize

Let's look a little deeper into starting the authentication request. There are two required parameters:

  • client_id - The client ID issued to your application by Kiva (see My Apps)
  • response_type - This value must be set to "code".
  • oauth_token - The request token previously obtained.
  • oauth_callback - The endpoint to which the authorization code will be returned. This must match the pre-registered value for your application. When using the Out Of Band flow this parameter must be set to “oob”.

There are also two optional parameters which we strongly recommend you use:

  • scope - A comma separated list of scopes that allow access to different potential resources. This will default to “access”, which will provide basic user information. Other scopes can be found in the API documentation.
  • state - This value is used by your application to correlate requests or otherwise track state across the authorization process. It can be set to any value and Kiva will maintain the value of this parameter for you in all request responses or redirects. If your application uses browser redirects in the authorization flow we strongly recommend you include a random session value in this parameter to prevent cross-site request forgeries.

All parameters are provided in the query string using the "application/x-www-form-urlencoded" format. Here's an example:

https://www.kiva.org/oauth/authorize?client_id=org.lenderweb&response_type=code&oauth_callback=https%3A%2F%2Flenderweb.org%2Fkiva_oauth_callback&state=6ED1279AB3340E9&oauth_token=eBe.phQZwWAHopJ6i2jRiVd-jRFK-7dduAIreRj-J;org.lenderweb.test-app

At this point the user will be prompted for login to Kiva (if necessary) and then given the option to grant the access to your application.

If the user approves this request the user will be redirected to the Redirect URI registered for your application along with the following parameters in the query string:

  • oauth_verifier - An authorization code valid for a short period of time which you can exchange for an access token.
  • oauth_token - The request token sent to the authorize page.
  • scope - A list of strings representing the scope of permissions granted by this authorization.
  • state - The same value of state which you originally provided to the application.

If the user does not approve your request or if there is an error with your request (invalid client_id, etc.) you will likely not receive a response. If possible, however, Kiva will return an error response to the Redirect URI with the following parameters:

  • error - A short string used to help determine the error. If the user explicitly denies access to your application this value will be "access_denied".
  • error_description - Optional. A human-readable string to help developer better understand the error.
  • state - The same value of state which you originally provided to the application.

REMEMBER: If you are using the Out Of Band flow there is no redirect. It is your application's responsibility to have the user enter the code in your application using the UI you provide.

Obtaining an Access Tokens

When your application is authorized by a user you are returned a short-lived one-time use credential or authorization code which you must subsequently exchange for an access token. This exchange is done using the oauth/access_token API:

POST https://api.kivaws.org/oauth/access_token
WARNING: Once again, if you are trying to sign your requests manually, don’t. Use a library: http://code.google.com/p/oauth/

This method must be called via HTTPS using the POST method with parameters passed in the HTTP request body. Note the oauth_verifier is the authorization code obtained from the user authorization flow.

If your request is successful the server will respond with a JSON object with the following properties:

  • oauth_token - The token identifier.
  • oauth_token_secret - The token key. This key should be protected securely as with all user private data.
  • scope - A list of strings representing the scope of permissions granted by this authorization.

Note that the access token is represented by three properties: oauth_token, oauth_token_secret and scope. You'll need to safely store all three of these values to make authenticated requests to the API.

If your request is rejected you will be returned a standard OAuth 1.0a error response. Your request may be rejected for any number of reasons including:

  • The authorization code expired. Authorization codes are short-lived and must be exchanged for tokens shortly after the authorization flow.
  • The authorization code has already been used. Authorization codes can only be exchanged once for an access token. The server may reject even if the first attempt to exchange the code was invalid.
  • Your client authentication does not match the client ID used in the corresponding authorization request.
  • Your Authorization header is incorrectly calculated, malformed, or corresponds to an invalid or restricted client.
  • Failure to use HTTPS for the request.
  • Missing or invalid parameters or any other errors in the construction of your POST request.

Remember, the access token issued to your application is sensitive information that should be kept private as it allows persistent access or modification of the user’s private data. Your application should never transmit the token key over insecure or unencrypted channels, and it should take appropriate measures to safeguard the token from theft and authorized use.

Registering

The App Dashboard gives you an interface to register and manage your applications.

Register a New Application

    To register a new application, click on Register a New Application under the My Apps tab. You will be presented with a form with the following options:

  • Name - Choose a name that fits your own branding. Do not to use generic names, such as Kiva App.
  • Description - Be as descriptive as you can. By the time you finish you app, it will probably be completely different to what you intended at the begining. So be sure to come back an update this!
  • Can your app keep secrets? - If your app will reside on a client device, such as a mobile phone, then it can't be trusted to keep a secret. If your app will be on a web-server, or other closed environment, it can be trusted.
  • Callback URI - Leave this blank for Out-of-Band authentication or if you're not yet sure which OAuth method and callback you'll use.
  • App ID - If your app already uses an App ID, enter it here. Otherwise, we'll generate one for you. Just letters, numbers, dashes and dots, please.
  • Website - Where can users access your app or find out more about it? If you want to publish your app, you'll need a website.
  • Icon - Users will see this when prompted to authorize your application.

Modifying an Application

Select the App you want to modify from the left menu under the My Apps tab. From here you can use the Edit button to modify your applications properties.

Getting to your OAuth details

All apps that use OAuth must be registered with Kiva.

To get the OAuth details you'll need to authenticate your application, select the App from the left menu under the My Apps tab. You will be taken to a page where you can get your OAuth Client ID and Client Secret. You application will need these to authorize via OAuth.

Kiva