January 23, 2021
Hot Topics:

Authenticating Users with a Sinatra API, Page 2

  • By Jason Gilmore
  • Send Email »
  • More Articles »

Returning JSONP

One typical reason for creating an API is to provide authorized third-parties with access to the API interface in order to at a minimum retrieve the data made available via the API, and potentially even manipulate the data using other defined routes. These days it's become very common to perform these API requests using Ajax, sending the request to the desired API endpoint and receiving JSON-formatted data in return. However, it's not possible for JavaScript to connect to another server other than the one upon which the JavaScript script resides, due to a security policy known as same origin. One great workaround to this dilemma is a variant of JSON known as JSONP, or JSON with padding. Although Sinatra doesn't by default support JSONP, it's easy to add JSONP capabilities using the sinatra-jsonp gem:

$ gem install sinatra-jsonp

Once installed, revise app.rb to look like this:

require 'sinatra'
require "sinatra/jsonp"

museums = [
  "The Louvre",
  "The Butler Institute",
	"Doria Pamphilj"

get '/museums' do
  JSONP museums

Restart your Sinatra application and reload the webpage. You'll see the following output:

["The Louvre","The Butler Institute","Doria Pamphilj"]

Incidentally, repeatedly restarting your Sinatra application quickly becomes tedious. Check out the shotgun gem, which will automatically restart your app every time it detects changes to the script.

Authenticating Users via an API Key

Most APIs require users to supply a valid API key with each request, which is subsequently checked against a database in order to ensure the requesting client is allowed to communicate with the API. While Sinatra doesn't offer any native authentication capabilities, it's pretty easy to incorporate such a feature into your application. Such a solution is explained in this Stack Overflow post.


Are you doing anything interesting with Sinatra? So far I'm having a blast, and would love to hear about how you're getting along with it in the comments!

About the Author

Jason Gilmore -- Contributing Editor, PHP -- is the founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board.

Originally published on https://www.developer.com.

Page 2 of 2

This article was originally published on September 19, 2011

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date