I've been playing with all sorts of API's lately, and one of the most complicated (for the sake of being complicated), is the Geocaching API. They use OAuth for connection. To obtain access (Key/Secret) you need to go through their process.
I am using CakePHP for this demonstration, and with CakePHP there is an excellent OAuth component which is what I am using. Find it here.
Lets say you have the Consumer Key/Secret now. Their OAuth process is a little funky, if you've ever used one before. Here's the broad-strokes view:
- You connect to their staging server, passing them your Consumer Key and Consumer Secret. Url is https://staging.geocaching.com/OAuth/oauth.ashx
- Their server will respond with a request token object. You pass the Token's key and the user to -- the same url you got the request token from: https://staging.geocaching.com/OAuth/oauth.ashx
- Once the user okay's your application, Geocaching.com will redirect the user back to the callback url with the OAuth verifier and the OAuth Token. ALMOST there.
- Send the request token (From step 2) and the OAuth Verifier and OAuth Token (Step 3) to what url? Oh it's https://staging.geocaching.com/OAuth/oauth.ashx again.
- The response from step 4) will look the same as the response from step 2, but alas, you are finally finished. They Access Token is the "Key" property in the OAuth Token Object. Save this to the user's session and use it for all requests to their API.
The following is the code in CakePHP.
Sending a POST request to geocaching.comGeocaching.com's API is a little clunky in terms of POST requests. A few things to remember.
- When sending a request, the Content-Type must be 'application/json'
- Even though its a POST request, in order to get the format back in jason, you must append the url (Like a GET request) eg: https://geocaching.com/api/geocaches?format=Json
Enough talk. Here is a sample POST request.
As for GET requests, there's nothing magic about those: Notice 'format' key/value pair has been moved into the $data array. This is because we are using the GET method in HttpSocket. The $data is url encoded and passed as part of the URL for the get request, so putting it in the $data as expected, unlike when using POST.
Definitely one of the weirder API's I have run into, but Geocaching is awesome, and I encourage everyone to get out there and try it. Developers should definitely tap into the API and see what kinda cool stuff you can do with it! Happy Geocaching!