Unable to pass headers correctly with httpc

Hi folks,

I am trying to export a page from Notion by using the Notion API.
It works in my Bash-script, but I’m not able to recreate it in Elixir.
Please help! :slight_smile:

This is my working Bash-script:

#!/usr/bin/env bash

NOTION_API_KEY="secret-key"
PAGE_ID="loremlorme"
PAGE_ENDPOINT="https://api.notion.com/v1/blocks/$PAGE_ID/children"

echo $PAGE_ENDPOINT
curl $PAGE_ENDPOINT \
  -H 'Authorization: Bearer '"$NOTION_API_KEY"'' \
  -H "Notion-Version: 2022-06-28"

And my non-working Elixir version.
What am I doing wrong?

defmodule EasySolutions.HTTPFetcher do
  @notion_api_key "SECRET"

  def fetch_url(page_id) do
    :inets.start()
    :ssl.start()

    page_endpoint = "https://api.notion.com/v1/blocks/#{page_id}/children"


    # The keys must be charlists, othwerwise the request will fail. 
    headers = [
      {~c"Authorization: Bearer", ~c"#{@notion_api_key}"},
      {~c"Notion-Version:", ~c"2022-06-28"}
    ]

    IO.inspect(headers)

    # Make the HTTP GET request with headers
    case :httpc.request(:get, {page_endpoint, headers}, [], []) do
      {:ok, {{"HTTP/1.1", 200, "OK"}, _headers, body}} ->
        {:ok, body}

      {:ok, {{"HTTP/1.1", status_code, status_reason}, _headers, _body}} ->
        {:error, "Failed to fetch URL. Status: #{status_code} #{status_reason}"}

      {:error, reason} ->
        # Handle request error
        {:error, reason}
    end
  end
end

httpc is going to turn key/value pairs into headers, so you shouldn’t include the : here:

    headers = [
      {~c"Authorization", ~c"Bearer #{@notion_api_key}"},
      {~c"Notion-Version", ~c"2022-06-28"}
    ]
2 Likes

Thanks, that was it! :smiley: