Using the OpenGraph API is very simple

But who doesn’t love a little copy and paste action? Below are links to example code for various languages.

If there is a language you think we are missing please let us know!

Coder at a Computer

Examples

Ruby

Ruby

C#

C#

Php

Php

NodeJS

NodeJS

JQuery

JQuery

Ruby Open Graph Example

The following Ruby example shows how a user might use Opengraph.io to get a website’s title, description, and icon given a URL. This example makes use of ExpressJS to proxy the request from a web user onto the OpenGraph.io API. This approach is often more appropriate in applications than sending traffic directly to OpenGraph.io’s server in that you have the ability to hide your API token and you can also perform any pre/post processing on the server rather than bogging down the client’s browser. The need for a function like this is very common when creating an application that posts content onto social media sites such as Facebook (see screenshot to the right) or Linkedin where the user wants to control how the link is displayed. If you would like more examples of how to use this the OpenGraph API, please check out the README for our Ruby module.

Open Graph Results

Ruby Code

require 'opengraph-io'

opengraph = OpenGraphIO.new({app_id: '!!!!YOUR_APP_ID!!!'})

ogData = opengraph.get_site_info('https://github.com')

siteDescription = ogData["hybridGraph"]["description"]

print siteDescription

check

To get the code above working, create a new directory and change into that directory from the command line (Linux or OSX)

mkdir example & cd example

check

Next, install the Ruby opengraph-io package

gem install -user-install opengraph-io

check

Finally, run the script which outputs the hybrid description of the site as gathered by OpenGraph.io

ruby test.rb

C# Open Graph Example

The following C# .NET example shows how a user might use Opengraph.io to get a website’s title, description, and icon given a URL. This example makes use of .NET system libraries and NewtonSoft’s popular JSON.NET library to retrieve and parse results from the OpenGraph.io API. The need to gather information like this is very common when creating an application that posts content onto social media sites such as Facebook (see screenshot to the right) or Linkedin where the user wants to control how the link is displayed.

Open Graph Results

C# Code

using System;

using System.Net;

using System.IO;

using System.Json;


namespace CSharpDemo

{

    class MainClass

    {

        public static void Main (string[] args)

        {

            var url ="http://cnet.com";

            var urlEncoded = Uri.EscapeDataString(url);

 

            var requestUrl = "https://opengraph.io/api/1.1/site/" + urlEncoded;

 

            ⁄⁄ Make sure to get your API key! No need for a CC

            requestUrl += "?app_id=XXXXXXXXXXXXXXXXXXXXXXXX";

 

            var request = WebRequest.Create(requestUrl);

            request.ContentType = "application/json;";

 

            string text;

 

            var response = (HttpWebResponse)request.GetResponse();

 

            using (var sr = new StreamReader(response.GetResponseStream()))

            {

                text = sr.ReadToEnd();

 

                dynamic x = JsonConvert.DeserializeObject(text);

 

                Console.WriteLine("Title\t\t" + x.hybridGraph.title);

                Console.WriteLine("Description\t" + x.hybridGraph.description);

                Console.WriteLine("Image\t\t" + x.hybridGraph.image);

            }

        }

    }

}

PHP Open Graph Example

The following PHP example script demonstrates how a user might use Opengraph.io to get a website’s title, description, and icon given a URL. This example really just shows how to get and parse the data (normal JSON)… once you have the data you can throw it on a page similar to the way that Facebook shows link information.. The OpenGraph.io API will pull down the requested URL and determine the appropriate information from the site depending on what is available.

Open Graph Results

PHP Code

$siteUrl = 'http://cnet.com';

$requestUrl = 'https://opengraph.io/api/1.1/site/' . urlencode($siteUrl);

 

⁄⁄ Make sure you include your free app_id here!  No CC required

$requestUrl = $requestUrl . '?app_id=XXXXXXXXXXXXXXXXXXXXXXXX';

 

$siteInformationJSON = file_get_contents ($requestUrl);

$siteInformation = json_decode($siteInformationJSON, true);

 

print ';Title\t\t'; . $siteInformation['hybridGraph']['title'] . '\n';

print 'Description\t' . $siteInformation['hybridGraph']['description'] . '\n';

print 'Logo URL\t' . $siteInformation['hybridGraph']['image'] . '\n';

check

To get the code above working, copy the code above into a file like test.php. Then run the following command

php test.php

NodeJS Open Graph Example

The following NodeJS example shows how a user might use Opengraph.io to get a website’s title, description, and icon given a URL. This example makes use of ExpressJS to proxy the request from a web user onto the OpenGraph.io API. This approach is often more appropriate in applications than sending traffic directly to OpenGraph.io’s server in that you have the ability to hide your API token and you can also perform any pre/post processing on the server rather than bogging down the client’s browser. The need for a function like this is very common when creating an application that posts content onto social media sites such as Facebook (see screenshot to the right) or Linkedin where the user wants to control how the link is displayed.

Open Graph Results

Javascript Code

var opengraph = require('opengraph-io')({appId: 'xxxxxx'}) ⁄⁄ <-- Enter your app_id!

var express = require('express');

var app = express();

 

app.get('/site/info', function (req, res) {

  var siteUrl = req.query['url'];

 

  opengraph.getSiteInfo(siteUrl, function(err, siteInfo){

    console.log('hey err, err);

    console.log('hey result', siteInfo);

    res.json(siteInfo);

  });

 

});

 

app.listen(3000, function() {

  console.log('Example app listening on port 3000!');

  console.log('Test this proxy with the following url:', 'http://localhost:3000/site/info?url=https%3A%2F%2Fnytimes.com');

});

check

To get the code above working, create a new directory and change into that directory from the command line (Linux or OSX)

mkdir example & cd example

check

Next, initialize the node package. Enter the information you are prompted for after entering the following

npm init

check

Next, install the ExpressJS and https packages

npm install express opengraph-io

check

Finally, create a server.js file with the contents above and start the app up

node server.js

JQuery Open Graph Example

The following JQuery example shows how a user might use Opengraph.io to get a website’s title, description, and icon given the URL. The need for this sort of information is very common when creating an application that posts content onto social media sites such as Facebook (see screenshot to the right) or Linkedin where the user wants to control how the link is displayed.

Open Graph Results

jQuery Code

var url = 'http://cnet.com';

var urlEncoded = encodeURIComponent(url);

var apiKey 'xxxxxxxxxx';

 

⁄⁄ The entire request is just a simple get request with optional query parameters

var url = 'https://opengraph.io/api/1.1/site' + urlEncoded + '?app_id=' + apiKey;

 

$('#loadOpenGraphData').click(function(){

  $.getJSON(requestUrl, function(json) {

    console.log('hey result', siteInfo);

 

    ⁄⁄ Throw the object in the console to see what it looks like!

     console.log('json', json

 

    ⁄⁄ Update the HTML elements!

    $('#title').text(json.hybridGraph.title);

    $('#description').text(json.hybridGraph.description);

    $('#icon').attr('src', json.hybridGraph.image);

  });

});