Grab card data from url

Yes, but you’ll need an intermediary.

Here’s an example using OpenGraph.io to retrieve Open Graph data. Their free tier is limited to 100 requests per month. You will need to sign up for an account (no credit card required) to obtain an API key.

config.toml:

[params]
opengraph_io_api_key = "paste_your_api_key_here"

Markdown:

{{< og-summary "https://www.washingtonpost.com/news/voraciously/wp/2020/07/07/a-classic-french-dessert-gets-a-savory-spin-with-this-bell-pepper-and-zucchini-clafoutis/" >}}

{{< og-summary "https://www.thetimes.co.uk/edition/sport/liverpool-take-step-closer-to-record-total-j00kjjb7v" >}}

layouts/shortcodes/og-summary.html:

{{- $api_key := "" -}}
{{- $json := "" -}}

{{/* Get API key from config.toml. */}}
{{- with .Site.Params.opengraph_io_api_key -}}
  {{ $api_key = . }}
{{- else -}}
  {{- errorf "The '%s' shortcode requires an API key for opengraph.io. Please set '[params] opengraph_io_api_key' in config.toml. See %s" .Name .Position -}}
{{- end -}}

{{/* Get JSON from OpenGraph.io. */}}
{{- with .Get 0 -}}
  {{- $url := replace . ":" "%3A" -}}
  {{- $url = replace $url "/" "%2F" -}}
  {{- $query := querify "accept_lang" "auto" "app_id" $api_key -}}
  {{- $request := printf "https://opengraph.io/api/1.1/site/%s?%s" $url $query -}}
  {{- $json = getJSON $request -}}
{{- else -}}
  {{- errorf "The '%s' shortcode requires a single positional parameter, a URL. See %s" .Name .Position -}}
{{- end -}}

{{/* Check status code returned by OpenGraph.io. */}}
{{- if ne (string $json.requestInfo.responseCode) "200" -}}
  {{ $msg1 := "The '%s' shortcode was unable to retrieve Open Graph data for %s." .Name $json.requestInfo.url }}
  {{ $msg2 := "The opengraph.io server response code was %s." (string $json.requestInfo.responseCode) }}
  {{ $msg3 := "See %s" .Position }}
  {{ errorf "%s %s %s" $msg1 $msg2 $msg3 }}
{{- end -}}

{{/* Output */}}
<h2>{{ $json.openGraph.title }}</h2>
<p>{{ $json.openGraph.description }}</p>
<p><a href="{{ $json.openGraph.url }}">Continue reading...</a></p>
<img src="{{ $json.openGraph.image.url }}" alt="">

Comments:

  1. The quality and type of OG data available depends on the publisher, and in some case the article itself. This is particularly true for images. Some publishers provide alternate text, width, height, some combination of these, or nothing at all.

  2. To see the entire JSON object returned by OpenGraph.io, place this in the shortcode:

    <pre>{{ jsonify (dict "indent" "  ") $json }}</pre>
    
  3. There are other ways to obtain OpenGraph data, including scrapers implemented in PHP and nodejs. This was the most expedient.

8 Likes