Wednesday, August 17, 2016

Developing Mobile Web Apps: When, Why, and How

There are 6.8 billion people on the planet, 5.1 billion of whom own a cell phone (source). And today, an ever-growing percentage of these devices are smartphones. According to a recent Pew Research Center Study, the number of users accessing the Internet on their smartphones has more than doubled in the past 5 years, as has the number of users downloading and using mobile apps. Of those who use the Internet or email on their phones, more than a third go online primarily through their handheld devices.
Indeed, mobile computing is becoming increasingly ubiquitous… and it’s awesome.
Except, of course, when it’s not.
As a mobile device user, few things are as frustrating and difficult to fat-finger-navigate as a poorly designed mobile web or native app.
And as a mobile app developer, few things can be as intensely irritating as striving to support as wide a range of mobile clients as possible, each of which has its own frustrating set of idiosyncrasies. Whether you choose to develop a mobile web, native, or hybrid app, the quest to support multiple mobile browsersmore-exotic devices, and platforms can be quite a gut wrenching experience indeed.
This web app development tutorial seeks to help you navigate different browsers and platforms.As a mobile device user, few things are as frustrating and difficult to fat-finger-navigate as a poorly designed mobile web or native app. And as a mobile app developer, few things can be as intensely irritating as striving to support as wide a range of mobile clients as possible, each of which has its own frustrating set of idiosyncrasies.
Of course, not every developer today needs to worry about supporting mobile clients. But the increasingly omnipresent nature of mobile devices and applications strongly suggests that those who don’t need to support mobile clients today will more than likely need to do so in the not-too-distant future. So if you’re not already thinking about mobile app development, you probably should be.

Mobile app: Web vs. native vs. hybrid (help me choose!)

As is true with most technology selections, there’s no one-size-fits-all answer when it comes to the type of mobile app to develop. There are numerous web app best practices to consider, not all of which are technical. Who is your target audience? Are they more likely to prefer a mobile web or a native app? What development resources do you have and which mobile technologies are they most familiar with? What is the licensing and sales model that you’re envisioning for your product?
Generally speaking (although there are always exceptions), the mobile web route is faster and cheaper than the native app route, especially when the objective is to support a wide range of devices. Conversely, there may be capabilities native to the mobile device (such as the movement sensor and so on) that are essential to your app, but which are only accessible via a native app (which would therefore make the mobile web app choice a non-starter for you).
And beyond the web vs. native question, a hybrid app may be the right answer for you, depending on your requirements and resource constraints. Hybrid apps, like native apps, run on the device itself (as opposed to inside a browser), but are written with web technologies (HTML5, CSS and JavaScript). More specifically, hybrid apps run inside a native container, and leverage the device’s browser engine (but not the browser) to render the HTML and process the JavaScript locally. A web-to-native abstraction layer enables access to device capabilities that are not accessible in mobile web applications, such as the accelerometer, camera, and local storage.
But whatever choice you make – whether it be mobile web, native or hybrid app – be careful to adequately research and confirm your assumptions. As an example for the purposes of this mobile web app development tutorial, you may have decided to develop a native app for e-commerce to sell your products, but according toHubspot, 73% of smartphone users say they use the mobile web more than native apps to do their shopping… so you may have bet on the wrong horse.
But whatever choice you make – whether it be mobile web, native or hybrid app – be careful to adequately research and confirm your assumptions.
And then, of course, there are the practical considerations of time and budget. As one of my favorite sayings goes, “faster, better, cheaper… pick any two”. While time-to-market and cost constraints are of paramount importance in web application development, it’s crucial not to compromise too heavily on quality in the process. It’s quite difficult to recover the confidence of a user who has had a bad first experience.
Indeed, mobile web, native, and hybrid apps are all radically different beasts, each with their own unique set of benefits and challenges. This development tutorial specifically focuses on methodologies and tools to employ, and pitfalls to avoid, in the development of highly functional, intuitive, and easy-to-use mobile web applications.
A critical best practice in determining how to develop a mobile web application is to know your customer.

Plan ahead (“if you don’t know where you’re going, you just might end up there…”)

Identifying your (or your customer’s) requirements is one of the most essential best practices in app development, mobile or otherwise. Carefully research the targeted capabilities to determine if they are achievable in a web app. It’s quite frustrating, and highly unproductive, to realize that one or more of your essential client functions aren’t supported, when you’ve already invested the time and resources to design the web-based interface and supporting infrastructure.
Another common gotcha for mobile web app developer newbies is to ass-u-me that web-based code for a desktop browser will work “as is” in a mobile browser. Not. There most definitely are differences and, if you’re not aware of them, they can definitely bite you. The HTML5 <video> tag’s autoplay functionality, for example, doesn’t work on mobile browsers. Similarly, the CSS transition and opacity properties are not supported (or at least are not consistently supported) in most mobile browsers nowadays. You will also have problems with some web API methods on a mobile platform, such as the SoundCloud music streaming API that requires Adobe Flash which is not supported on most mobile devices.
A common gotcha for mobile web app developer newbies is to ass-u-me that web-based code for a desktop browser will work “as is” in a mobile browser.
A particularly complicating factor in mobile web application development is that the lifespan of mobile devices tends to be much shorter than that of desktop displays (the average lifespan of a cell phone in the U.S. is around 21 months). These shorter device life spans, accompanied by constant releases of new mobile devices and technologies, yield an ever-changing landscape of to-be-targeted devices. While working in a browser does somewhat alleviate this issue by shielding you from a number of device-specific issues, you will still need to design a browser-based view that supports many different screen resolutions (as well as adjusting appropriately for landscape and portrait orientations).
Thought needs to be given as well to supporting Apple’s Retina Displays (liquid crystal displays that have a pixel density high enough that the human eye is unable to discern individual pixels at a typical viewing distance). Several Apple products – including the iPhone, iPod Touch, iPad, MacBook Pro, iPad Mini, and iPad Air – offer Retina displays. For a mobile web app in particular, it’s important to be aware that a Retina display makes low resolution images (which are typically served to mobile devices) look fuzzy and pixelation can occur. The best app development solution in these cases is to have the server recognize that the request is coming from a Retina device and to then provide an alternate higher resolution image to the client.
If you want to use some of the cool HTML5 stuff, remember to verify in advance that the functionality you’re looking for is supported across the device landscape that your customers are likely to be using. For example, in iOS 6 and above, there is no support for the navigator getUserMedia functionality since the camera is only accessible through native apps. Two great resources for checking what’s supported on specific devices and browsers are caniuse.com and html5test.com.
Remember to verify in advance that the functionality you’re looking for is supported across the device landscape that your customers are likely to be using.
CSS3 media queries can also help you provide customized content for each device. Here’s some example code for capturing different device characteristics, such as pixel density, screen resolution, and orientation:
/* For lower than 700px resolutions */
@media (max-width: 700px) { ... }
/* Same as last but with the device orientation on land scape */
@media (max-width: 700px) and (orientation: landscape) { ... }
/* Including width and orientation you can add a media type clause,
   in this case 'tv' */
@media tv and (min-width: 700px) and (orientation: landscape) { ... }
/* for low resolution display with background-image */
.image {
    background-image: url(/path/to/my/image.png);
    background-size: 200px 300px;
    height: 300px;
    width: 200px;
}
/* for high resolution (Retina) display with background-image */
@media only screen and (min--moz-device-pixel-ratio: 2),
only screen and (-o-min-device-pixel-ratio: 2/1),
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2) {
    -repeat;
        background-size: 200px 400px;
    /* rest of your styles... */
    }
}

Performance, performance, performance

“OMG, this thing is sooooo slow!” As a mobile web app developer, those are probably the very last words you ever want to hear from one of your users. You must therefore think carefully about how to reduce and optimize each byte and server transfer to reduce the user’s wait time. It’s unrealistic to expect that transfers will always be done over a WiFi network, and you should know that 60% of mobile web users say they expect a site to load on their mobile phone in 3 seconds or less (source). Similarly, Google found that, for every extra 5 seconds of load time, traffic dropped by 20% (and it is also worth noting that search engines look at load times as part of their calculation of page quality score).
60% of mobile web users say they expect a site to load on their mobile phone in 3 seconds or less.
As a part of this web app development tutorial, here are a few tips that can help optimize the performance of your mobile web app and minimize latency:
  • Image Optimization. Image load time is well-known to be one of the biggest performance issues affecting page load on mobile devices. Use of online image optimizers, such as smushit.com, can be helpful in addressing this issue.
  • Code compression. Compressing your JavaScript and CSS files, depending on the amount of code you have, can potentially have a significant impact on performance. A useful tool for compressing your code isrefresh-sh.com.
  • Database queries.
    • Some mobile device browsers don’t accept as many cookies as desktop browsers do, which can result in the need to execute even more queries than usual. Server-side caching is therefore especially crucial when supporting mobile web app clients.
    • Remember to employ the appropriate filters to preclude SQL query injection that could otherwise compromise the security of your site and server.
  • Content delivery networks (CDN). If you are planning to provide lots of videos, images, audio files, or other types of media, use of a CDN is highly recommended. Some of the more common commercial CDNs include Amazon S3Microsoft Windows Azure, and MaxCDN. The advantages of using a CDN are numerous and include:
    • Improved download performance. Leveraging a CDN’s resources enables you to distribute load, save bandwidth, and boost performance. The better CDNs offer higher availability, lower network latency, and lower packet loss. Moreover, many CDNs provide a globally distributed selection of data centers, enabling downloads to occur from a server closer to the user’s location (resulting in fewer network hops and faster downloads).
    • More concurrent downloads. Browsers typically limit the number of concurrent connections to a single domain, after which additional downloads are blocked until one of the previous downloads has completed. You can often see this limit in action when downloading many large files from the same site. Each additional CDN (on a different domain) allows for additional concurrent downloads.
    • Enhanced analytics. Many commercial CDNs provide usage reports that can supplement your own website analytics and which may offer a better quantification of video views and downloads. GTmetrix, for example, has an excellent website reporting tool for monitoring and optimizing the sources loaded on your site.

Your mobile web app development toolbox

“The right tools for the right job” is an age-old adage that applies as much to software development as it does to any other domain. This tutorial provides and introduction to some of the more popular and widely-used tools for mobile web app development, but bear in mind that there may very well be other tools that are the “right” ones for developing your mobile web app, depending on your requirements and available resources.

Mobile JavaScript Frameworks

As mobile web developers tend to face many of the same common challenges – such as cross-browser compatibility and inconsistent HTML and CSS in mobile browsers – frameworks have been developed (based on HTML5 and CSS3) that are specifically designed to address these issues and to work as flawlessly as possible on a wide array of smart phones and tablets. Most of these frameworks are lightweight, which helps facilitate fast mobile web browsing without compromising the look and feel of your site.
Broadening our view beyond the mobile landscape, if there is a single popular JavaScript framework worth mentioning, it is jQuery. If you’re familiar with the desktop version, I recommend trying jQuery Mobile for your mobile web app. It has a widget library that converts semantic markup into a gesture-friendly format, making operations easy on touch-screens. The latest version consists of a really lightweight code base that packs a punch with a lot of graphical elements that really can improve your UI.
Another alternative, Sencha Touch, is rapidly gaining market share as well. It offers excellent performance overall and helps produce a mobile web user interface that largely looks and feels like a native one. Its full-featured widget library is based on Sencha’s ExtJS JavaScript library.
Here are some key differences to consider when comparing jQuery Mobile and Sencha Touch:
  • Look and feel. Generally speaking, the look and feel of a Sencha Touch app is crisper and superior to that of a jQuery mobile app, but it is important to remember that such reactions do tend to be highly subjective.
  • Extensibility. jQuery Mobile offers lots of 3rd party extensions and is inherently designed to be highly extensible, whereas Sencha Touch is currently much more of a “closed” framework.
  • Device support. jQuery Mobile currently targets a larger cross-section of devices than Sencha Touch.
  • HTML “vs.” JavaScript. jQuery is largely HTML-centric (i.e., extending and manipulating existing HTML in JavaScript), whereas Sencha Touch coding is entirely JavaScript-based. (This is an example, incidentally, of the skill set of your development team being important to consider when making your technology selections.)
  • External dependencies. jQuery mobile requires jQuery and jQuery UI for DOM manipulation, whereas Sencha Touch has no external dependencies.
  • Learning curve. Most developers find the ramp-up time with jQuery to be less than that of Sencha Touch, perhaps fueled by the large percentage of web developers who are already familiar with the standard jQuery libraries.

Responsive Frameworks

An increasing number of responsive frameworks have begun cropping up in recent years, with two of the currently most popular being Bootstrap and Foundation. In short, responsive frameworks simplify and streamline web-based responsive UI design and implementation, encapsulating the most common layouts and UI paradigms into a reusable, performance-optimized framework. Mostly based on CSS and JavaScript, many of these frameworks are open-source, free to download, and easily customizable. Unless you have a highly peculiar set of requirements, it is likely that use of one of these frameworks will reduce the level-of-effort to design and implement your mobile web application.
Examining the two leading options, Bootstrap and Foundation, a few of the key differences to consider include:
  • Targeted platforms. While Bootstrap does support mobile, tablet, and desktop devices, it is primarily oriented toward desktop use. Foundation, on the other hand, is designed for essentially all screen sizes and types.
  • Browser compatibility. Bootstrap is compatible with IE7 or higher, whereas Foundation is only compatible with IE9 or higher.
  • Diversity of layouts and components. Bootstrap has a significantly larger collection of UI elements than is offered by Foundation.
  • Auto-resizing. With Foundation, the grid shrinks and stretches according to the current browser height and width, whereas Bootstrap only supports a pre-defined set of grid sizes based on a standard set of screen sizes.

Testing and debugging your mobile web app

Debugging mobile web apps can be tricky and somewhat frustrating, especially if you need to scrounge around for different devices to test on, or install SDKs for a (typically imperfect) emulation of the targeted client platforms.
In this context, one clear advantage of mobile web app development (as compared with native app development) is that you can utilize standard browser-based developer tools to debug your application. Based on my personal preference for remote debugging, the one I recommend in this app development tutorial is Chrome with its DevTools. Other standard options include Firefox with Firebug or Opera’s Dragonfly tools.
When learning how to develop web applications, look toward Chrome and its DevTools.
Some of the reasons I prefer Chrome with its DevTools include:
  • Mobile emulator in Chrome’s DevTools. This is perhaps alone sufficient reason to select Chrome for debugging of mobile web apps. Key features include emulation of touch events, user agent spoofing, network bandwidth throttling, geolocation overrides, device orientation overrides, and CSS Media Type Emulation.
  • Interactive editor. Ability to edit JavaScript or CSS on-the-fly.
  • Superior JavaScript debugger. Allows for DOM breakpoints and provides the ability to profile your JavaScript code execution time.
  • Built-in JSON and XML viewers. Avoids the need for any plugins to inspect server responses.
  • Support for the Android Debug Bridge (ADB) protocol directly over USB. Facilitates easy instantiation of a remote debugging session. (Here is a good tutorial by Google on how to start remotely debugging in Chrome.)
  • Dynamic inspection of resources. Allows you to inspect your app’s local data sources, including IndexedDB or Web SQL databases, local and session storage, cookies, and Application Cache resources. You can also quickly inspect your application’s visual resources, including images, fonts, and style sheets.
To test the layout and cross browsing compatibility of your web app, you can also use some helpful online tools, such as BrowserStack. Just enter the URL for your application, select the browser, version, and operating system, and you’ll get the emulated view (and load speed) of your site in that environment. Another useful tool for the this purposes is CrossBrowserTesting.

Wrap up

With the continued rapid expansion of the number, variety and sophistication of mobile devices on the market and in use today, the need for effective, user-friendly, high performance mobile applications is likely to increase substantially. Being able to develop these applications intelligently and efficiently will therefore continue to be of paramount importance.
Many factors must be considered when choosing between the web, native, and hybrid options for mobile applications. Each has its own advantages, but mobile web apps will often represent your most efficient development (and therefore time-to-market) option. Should you choose to go down that path, I hope this web app development tutorial helps get you more directly and successfully to your destination.
This article was written by  TOMAS AGRIMBAUa Toptal freelance developer.

Wednesday, August 10, 2016

Social Network APIs: The Internet’s Portal to the Real World

Social network APIs have come a long way since Google released the first version of its YouTube API in May 2008 and Facebook released the first version of the Graph API in April 2010. Today, these APIs give you the opportunity to query social network platforms for posts, users, channels, and demographic data. They even let you create your own service or find out more about your user base.
In this article, we will examine the ways we can utilize some of the popular social network APIs:
  • Facebook (Graph and Marketing API)
  • Instagram
  • Twitter
  • YouTube
  • Pinterest
We will also discuss their limitations, and explore some of the useful tools that are available for use with these APIs. Later in the article, we will also take a look at how to integrate these APIs in any Rails application.
Social Network APIs: The Internet’s Portal to the Real WorldUse social network APIs to get to know your users better than they know themselves.
I will focus on one social network API at a time and explain its capabilities, limitations and available tools. There will be a matrix with the different APIs and their properties for better comparison later in this article.
In order to use the APIs you will first need to setup an app that creates queries on behalf of your application with OAuth based requests. Users will authenticate against your app and you can then access their data with the resulting user access-token.

FACEBOOK

The now outdated FQL (Facebook Query Language) used to be a SQL-like query language that could be used to access all data from Facebook.
Facebook released the first version of its Graph API in April 2010. The most recent version at the time of writing this article is 2.6 which was introduced on April 12, 2016. It is a low level HTTP-based API that can be used to query data, create posts, and even create automated ad campaigns.

Tools

The Graph API Explorer is the most commonly used tool when working with the Facebook API. It lets you execute Graph API queries in the browser and examine the results: You can use one of your app’s access tokens or create one on the fly with selected scopes.

Capabilities

The Graph API is a REST-based API that lets you create, update, and delete objects per HTTP request on certain nodes.

Access Token

To run queries against the Graph API, you need an access token that is obtained as soon as a user successfully authorizes in your app. The access token should be stored by your application.

Scopes

Scopes determine which actions can be performed on behalf of a user. The application asks for certain scopes when a user authorizes in an app. The publish_actions scope, for example, lets an app publish posts on behalf of a user. The email scope lets the app read the user’s email. A full overview over all scopes is listed in the official documentation.
Certain scopes like the publish_actions or ads_management require a review by Facebook prior to the release of the app.

Examples

To demonstrate how the Graph API works, I will show you how to read, create, update, and delete posts with the API.
To get your own posts, you can execute the GET query /me/posts. The result will be a JSON string with a list of posts, including their message, created_time, and id.
To get more data about your posts, you can extend the query with fields as query parameters. For example, the query me/posts?fields=reactions, picture will give you the post’s picture and reactions.
To create a post, you can simply send a POST action against the edge feed, e.g. me/feed, with parameters such as message: hello world. The Graph API will return a JSON object with the ID of your created post. You can then view the post at the address http://facebook.com/[post_id].
To update a post, you can send a POST request to the post’s node with the fields to be updated as parameters; e.g., /[post_id] and params like Message: lorem ipsum. A success indicator with a value of true or false will be returned.
To delete a post, you can simply make a DELETE request to the node with the post ID (e.g., /[post_id]). The return value will be a JSON object with a success value of true or false.
A full overview over all nodes and actions is available in the Graph API Reference.

Marketing API

The marketing API deserves special mention because it is a powerful tool to manage Facebook ads and get ad insights through your application.
It works the same way as other Graph API methods. However, you need the ads_management scope in order to get access to the user’s ads. Facebook also needs to review your app before you can publish it.

Testing

Once you create your app, it is in development mode and automatically visible in your app dashboard (i.e., https://developers.facebook.com/apps/).
In development mode, only admins, devs, and testers have access to your app. You can add testers and admins in the roles section of your app dashboard.

Review Process

When adding certain permissions,Facebook needs to review your app before you can publish it. The review process is defined by this set of guidelines.
In order to submit certain items for review, you can simply add them in the App Review section of your app dashboard. Facebook will then guide you through the review process and you will be alerted once your app is approved.

Limitations and Workarounds

Rate Limits

An app can make 200 calls per hour per user in aggregate. If you reach that limit, your API calls will result in error.

Searching for Posts on Facebook

Facebook restricts searching for posts and tags on Facebook through the Graph API and FQL. However, you can use the Google Search API to search for public Facebook posts and then use the post-id in the URL to retrieve more information about specific posts through the Graph API.

Getting Custom Audience Data

Audience Insights on Facebook is a powerful research tool to learn more about a particular audience based on interests, demographics, or a other attrributes (e.g., a collection of email addresses).
However, I have not found a way to automatically create audience insights through the ad API. Let us know in the comments if you have any creative ideas or suggestions for this.

INSTAGRAM

The Instagram API was first released in April 2014 and allows you to build apps that analyze user posts and help users to manage their own posts.

Tools

Since the API console by Instagram is deprecated at the time of this article, I recommend using Apigee for testing purposes in your browser.

Capabilities

The Instagram API is a REST-based API. All of its endpoints are described in their official documentation.

Access Token

To run queries against the Instagram API, you need an access token that is obtained as soon as a user authorizes in your app. In order for a user to receive an access token, he or she must be directed to your app’s authorization URL. The server will then redirect the user after authorizing your app and you will then be able to read the token.

Scopes

Your app can ask for different permissions. For instance, “basic” limits you to reading a user’s profile info and media. “public_content” lets you read any public profile and media on behalf of a user.

Examples

To demonstrate how the Instagram API works, I will go through some examples based on the media endpoint https://api.instagram.com/v1/media/popular.
This endpoint returns the currently popular media from Instagram if passed an access token as a parameter. The result will be a JSON array of posts containing, for each, its media ID, a link to its image, likes, comments, the user that posted it, and some other attributes.
You can use apigee to play around and find out more about the API endpoints and their parameters.

Testing

Every new app created on the Instagram platform starts in sandbox mode. This is a fully functional environment that allows you to test publicly available API endpoints before you submit your app for review.
To test your app, simply create a staging version and run all queries through that version instead of the live version that got through the review.

Review Process

Apps in sandbox mode can use any API endpoint, but are restricted to a limited number of users and media. It’s a great mechanism for developing and testing an app.
To go live and access all Instagram content, you will need to submit your application for review. Once reviewed, you will only be able to request the scopes for users for which your app was approved.

Limitations and workarounds

Demographic Analysis

At the time of writing this article, there is no way to get information about a public users’ age, gender, or interests, because Instagram does not provide you with that information.
In order to get demographics data about followers or a list of Instagram users, you would need to iterate over all of them and try to determine their age and gender or interests based on their followers or the information provided in their bio.
A good big data solution for this problem might be a valuable service to some companies.

Rate Limits

All rate limits on the Instagram platform are controlled by access token on a sliding 1-hour window. Live apps have higher rate limits than apps in Sandbox Mode. The global rate limit for a live app is currently 5,000 calls per hour.

TWITTER

The Twitter API was first released in September 2006. It is a public REST API that provides read and write access to Twitter data. Authentication is performed using OAuth. Responses are in JSON format.

Tools

Twitter has an API console tool powered by apigee that can be used to test requests in the browser.

Capabilities

The REST API lets you get a user’s tweets, followers, and followed people. You can also search for hashtags in other tweets.

Access Token

Twitter lets you create apps that users can authenticate against in return of an access token. The authentication model is OAuth.

Scopes

There are only two permissions that have to be set on the app’s setting page: Read only and Read and Write. The latter lets you create tweets and perform other post actions on behalf of a user.

Examples

To demonstrate the usage of the Twitter API I will retrieve the authorized user’s tweets. The result is a JSON array with the tweet’s images, favorites, retweets, urls, creation date, and other attributes. Use Apigee to play around and find out more about the API endpoints and their parameters.

Testing and Review Process

There is currently no review process or test mode available for the Twitter API.

Limitations and Workarounds

Demographic Analysis

There is currently no easy way to get demographic data from someone’s Twitter followers. The brute force approach would be to browse through each follower and try to get the data through their bio and linked social network accounts.
You can then make further assumptions based on the collected follower data through data analysis. Another way to get more insights is through Twitter’s paid enterprise API platform GNIP. Among other things, it lets you create audiences and get information about those through the API. The API is currently in BETA.

Rate Limits

Twitter has rate limits on a per-user basis and on a 15 minute basis. If your application has multiple tokens, you can simply alternate tokens for public operations in order to avoid reaching the limit.

YOUTUBE

The YouTube Data API was first introduced in January 2013. It lets you add YouTube features to your application, search for content, and analyze a YouTube channel’s demographics. It is an OAuth, token-based REST API that returns JSON responses.

Tools

The API Explorer lets you test unauthorized and authorized requests. You can run requests from your browser against the provided endpoints.

Capabilities

Among other things, you can work with activities, chats, live broadcasts, playlists, channels, videos, and subscriptions. Most of the endpoints require you to authorize with a YouTube account.

Access Token

The YouTube Data API supports the OAuth 2.0 protocol for authorizing access to private user data. Once a user has been authorized in your application, they will be redirected to your application where the access token should be saved.
In order to use OAuth 2.0 authorization, you first need to obtain authorization credentials in the Google developer console.

Scopes

The YouTube Data API currently supports the following scopes:
  • Force SSL - Manage your youtube account but only over an SSL connection.
  • Default - Manage your YouTube account. This scope is functionally identical to the youtube.force-ssl scope but does not require an SSL connection.
  • Read Only - View your YouTube account.
  • Upload - Upload YouTube videos and manage your YouTube videos.
  • Partner Channel Audit - Retrieve information that Multichannel Networks use as criteria to accept or reject a channel in their network.

Examples

As an example of usage of the Youtube Data API, the following request queries for videos with “coding” in their title and description:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=coding&key={YOUR_API_KEY}
The result is a JSON object containing the title, description, videoId, and channelId. You can use the latter to find out more about the channel.
The part parameter is required for any API request that returns a certain resource. The parameter identifies resource properties that should be included in an API response. For example, a video resource has the following parts: snippet, contentDetails, fileDetails, player, processingDetails, recordingDetails, statistics, status, suggestions, topicDetails.
All other parameters, except the API key, differ from call to call. Read more about it in the API reference guide.

PINTEREST

The Pinterest API was initially released in April 2015. It is a RESTful API that provides access to a user’s Pinterest data, such as their boards, pins, followers and more. The Pinterest API uses OAuth and allows both read and write permissions when interacting with a user’s content.

Tools

Like others, Pinterest provides an API Explorer to test their endpoints and run queries against them. You can have a look at all their tools here.

Capabilities

The Pinterest REST API allows you to create pins, boards and query Pinterest data with OAuth.

Access Token

Pinterest uses OAuth 2.0 to authenticate requests between your app and your users. All requests must be made over HTTPS.

Scopes

Scopes determine what an app can do on behalf of a user. Pinterest uses the following scopes:
  • none (must know the identifier): Use GET method on a user’s profile, board and Pin details, and the Pins on a board.
  • read_public: Use GET method on a user’s Pins, boards and likes.
  • write_public: Use PATCH, POST, and DELETE methods on a user’s Pins and boards.
  • read_relationships: Use GET method on a user’s follows and followers (on boards, users and interests).
  • write_relationships: Use PATCH, POST, and DELETE methods on a user’s follows and followers (on boards, users and interests).

Examples

To demonstrate the use of the Pinterest API, I will demonstrate how to read the user’s latest pins:
https://api.pinterest.com/v1/me/pins/?access_token={your_token}&fields=id,link,note,url,counts,board,created_atwill return a user’s pins with their id, link, note, url, likes, and repins.

Testing and Review Process

Apps are initially in development mode and must be submitted for review before they are released in production mode.

Limitations and workarounds

Demographic Analysis

There is no common way to get demographics data from a board. However,you can try to get a board’s followers and information about them from their bio and links to other social network accounts. A big data solution over the user’s common connections would also be a possibility.

Search for Pins

There is currently no way to search for pins with certain tags or keywords through the API. You can bypass that limitation by using the Google Custom Search API to search for results on Pinterest pins only and gather the pin ID through the URL. The ID can then be used to get information about the pin through the API.

Rate Limits

Each app (with a unique app ID) is allowed 1,000 calls per endpoint per hour for each unique user token.
Every API response returns a header that gives you an update about rate limits. X-Ratelimit-Limit is the rate limit for that specific request, and X-Ratelimit-Remaining is the number of requests you have left in the 60-minute window.
If you exceed your rate limit for a given endpoint, you’ll get a 429 “Too many requests” error code.

COMPARISON OF SOCIAL NETWORK APIS

VersionOAuthFormatDemographics
Facebookv2.6
Initial Release: April 2010
OAuth 2REST requests with JSON responsesSupported
Instagramv1
Initial Release: April 2014
OAuth 2REST requests with JSON responsesNot supported
Twitterv1.1
Initial Release: September 2006
OAuth 1REST requests with JSON responsesOnly supported with GNIP
YouTubev3
Initial Release: January 2013
OAuth 2REST requests with JSON responsesSupported
Pinterestv1
Initial Release: April 2015
OAuth 2REST requests with JSON responsesNot Supported

DEMO APPLICATION WITH DEVISE

Integrating these APIs in your new or existing applications, thanks to a plethora of social network API packages and libraries, is easier than ever. Most modern platforms and frameworks have time-tested third-party libraries that even unify the authentication aspect all these APIs into a single library with neat plugin architecture.
For this article, we will take a look at how Devise, a Ruby gem, does this ever so elegantly for Rails applications. Devise is a flexible authentication library based on Warden that implements authentication, registration, login, and data storage for multiple login providers. If you are more of a front-end guy and want to check something similar out for AngularJS, take a look at this article.
Devise, like most libraries of this class, doesn’t come built-in with support for any of the above mentioned social network APIs. Support for each of these social network API is provided through additional gems. The following gems are available for Rails authentication that cover the 5 providers discussed in this article:
gem 'omniauth-facebook'
gem 'omniauth-pinterest'
gem 'omniauth-twitter'
gem 'omniauth-google-oauth2'
gem 'omniauth-instagram'
One of the best things about Rails is that there are many plugins written by the open source community. These are distributed as gems. Listed under a central configuration file, these gems are managed by Bundler.
Since these only provide authentication, registration, login, and storage for each of those providers, we will also need to get the following gems for the actual API clients:
gem 'twitter' # https://github.com/sferik/twitter
gem 'instagram' # https://github.com/facebookarchive/instagram-ruby-gem
gem 'koala' # (Facebook API) https://github.com/arsduo/koala
gem 'google-api-client' # (YouTube API), https://github.com/google/google-api-ruby-client
gem 'pinterest-api' # https://github.com/realadeel/pinterest-api

Omniauth and Authentication

In order for a user to authorize your app with your provider, you can simply provide a link with the following path:
omniauth_authorize_path('user', :facebook)
omniauth_authorize_path('user', :instagram)
...
In order to react on the callback after authenticating a user you can define a OmniauthCallbacksController with the scopes as functions like:
class AuthenticationsController < Devise::OmniauthCallbacksController
  def facebook
    if request.env["omniauth.auth"]
   ...
    end
  end
end
That is the place to add a new Authentication model with the token and data into your application:
authentication = where(provider: omniauth.provider, user_id: user.id)
  .first_or_create do |auth|

    auth.user = user
    auth.uid = omniauth.uid

    auth.secret = omniauth.credentials.secret
    auth.token =  omniauth.credentials.token
    ...
end

Making API Calls

Here is an example of how to use Koala to query the Facebook API. The rest of the providers work more or less similarly and are documented in the gem’s README.
This is how you get your user data using Koala:
authentication = user.authentication_for_provider(:facebook)
token = authentication.token
api = Koala::Facebook::API.new(token)
results = api.get_object("me")
You can then use the JSON result returned by the API. Source code of this demo application is available on GitHub.

WRAP UP

Social network APIs provide you with a powerful tool to query the large data set of social networks and collect big data for your application. You can build a service on top of these APIs or use them to enhance your own application and user insights.
Rails and the available gems make it easy to integrate these APIs into your rails app and query the interfaces with an abstraction layer between your app and the API.
This article was written by Behsaad Ramez, a Toptal Ruby developer.