OpenGraph.io

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 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		" + x.hybridGraph.title);
                Console.WriteLine("Description	" + x.hybridGraph.description);
                Console.WriteLine("Image		" + 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		' . $siteInformation['hybridGraph']['title'] . '\n';
print 'Description	' . $siteInformation['hybridGraph']['description'] . '\n';
print 'Logo URL	' . $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

NodeJs 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 requestUrl = 'https://opengraph.io/api/1.1/site/' + urlEncoded + '?app_id=' + apiKey;

$('#loadOpenGraphData').click(function(){
  $.getJSON(requestUrl, function(json) {
    console.log('hey result', json);

    // 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);
  });
});

Python Open Graph Example

Python is one of the most popular languages for web scraping, data extraction, and building AI applications. The following example shows how to use the OpenGraph.io API with Python to extract metadata from any URL. This is useful for building link previews, populating content databases, or feeding data into LLM pipelines and RAG applications.

Open Graph Results

Python Code


import requests

# Replace with your actual app_id
app_id = 'xxxxxx'
target_url = 'https://github.com'

# Make the API request
api_url = f'https://opengraph.io/api/1.1/site/{requests.utils.quote(target_url, safe="")}'
response = requests.get(api_url, params={'app_id': app_id})

if response.status_code == 200:
    data = response.json()
    hybrid = data.get('hybridGraph', {})
    
    print(f"Title: {hybrid.get('title')}")
    print(f"Description: {hybrid.get('description')}")
    print(f"Image: {hybrid.get('image')}")
else:
    print(f"Error: {response.status_code}")
check

First, make sure you have Python 3 installed. Then install the requests library

pip install requests

check

Save the code above to a file (e.g., opengraph_example.py) and run it

python opengraph_example.py

Go Open Graph Example

Go is known for its speed and simplicity, making it a solid choice for building high-performance web services and CLI tools. This example shows how to call the OpenGraph.io API using Go's standard library. Great for building microservices that need link metadata or integrating web scraping into your backend.

Open Graph Results

Go Code


package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
)

func main() {
    appID := "xxxxxx" // Replace with your app_id
    targetURL := "https://github.com"

    apiURL := fmt.Sprintf(
        "https://opengraph.io/api/1.1/site/%s?app_id=%s",
        url.QueryEscape(targetURL),
        appID,
    )

    resp, err := http.Get(apiURL)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)

    var result map[string]interface{}
    json.Unmarshal(body, &result)

    if hybrid, ok := result["hybridGraph"].(map[string]interface{}); ok {
        fmt.Printf("Title: %v\n", hybrid["title"])
        fmt.Printf("Description: %v\n", hybrid["description"])
        fmt.Printf("Image: %v\n", hybrid["image"])
    }
}
check

Make sure you have Go installed (go.dev). Save the code to main.go and run it

go run main.go