0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

URL短縮APIを使って短縮URLを自動生成する方法【curl / JavaScript】

0
Posted at

はじめに

Webサービスや社内ツールを作っていると、長いURLを自動的に短縮したい場面があります。

たとえば、

  • SNS投稿用のURLを短くしたい
  • QRコード用のURLを管理したい
  • システムから短縮URLを自動発行したい
  • キャンペーンごとにリンクを管理したい

といったケースです。

この記事では、nly.kr のURL短縮APIを使って、curlJavaScript から短縮URLを作成する方法を紹介します。

今回使用するAPIのドキュメントはこちらです。


APIの基本仕様

エンドポイントは以下です。

POST https://nly.kr/api/shorten

Content-Type は以下を使用します。

application/x-www-form-urlencoded

認証にはAPIキーが必要です。

推奨されているヘッダーは X-API-Key です。

X-API-Key: your_API_KEY

Authorization: Bearer 形式も利用できます。

Authorization: Bearer your_API_KEY

レスポンスをJSONで受け取るため、以下も指定します。

Accept: application/json

パラメータ

短縮URLの作成には、以下の2つのパラメータを送信します。

パラメータ 必須 内容
url String Yes 短縮したい元URL(http / https)
category String Yes URLのカテゴリキー

category も必須です。

たとえば aidev など、APIドキュメントに記載されているカテゴリキーを指定します。

この記事では例として ai を使用します。


curlで短縮URLを作成する

最も簡単な例です。

curl -X POST "https://nly.kr/api/shorten" \
  -H "X-API-Key: your_API_KEY" \
  -H "Accept: application/json" \
  -d "url=https://example.com" \
  -d "category=ai"

your_API_KEY の部分を自分のAPIキーに変更します。

元URLとして送信しているのは、

https://example.com

です。

正常に処理されると、JSON形式で短縮URLが返されます。


レスポンス例

成功時のレスポンスは次のような形式です。

{
  "status": "success",
  "short_url": "https://nly.kr/Ab3XkQ",
  "original_url": "https://example.com",
  "code": "Ab3XkQ",
  "member_idx": 123,
  "category": "ai"
}

実際に利用するときは、通常 short_url を取得すれば十分です。

たとえばJavaScriptなら、

console.log(data.short_url);

のように利用できます。


JavaScript(fetch)から呼び出す

JavaScriptでは fetch() を使って呼び出せます。

const apiKey = "your_API_KEY";
const longUrl = "https://example.com";
const category = "ai";

fetch("https://nly.kr/api/shorten", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "X-API-Key": apiKey,
    "Accept": "application/json",
  },
  body: new URLSearchParams({
    url: longUrl,
    category: category,
  }),
})
  .then(async (response) => {
    const data = await response.json().catch(() => null);

    if (!response.ok) {
      throw {
        status: response.status,
        data: data,
      };
    }

    return data;
  })
  .then((data) => {
    console.log("Short URL:", data.short_url);
  })
  .catch((error) => {
    console.error(
      "ERROR",
      error.status || "",
      error.data || error
    );
  });

成功すると、たとえば次のような短縮URLを取得できます。

https://nly.kr/Ab3XkQ

これをデータベースに保存したり、SNS投稿やメール、QRコード生成などに利用できます。


Bearer認証を使う場合

X-API-Key の代わりに Authorization ヘッダーを使用することもできます。

curl -X POST "https://nly.kr/api/shorten" \
  -H "Authorization: Bearer your_API_KEY" \
  -H "Accept: application/json" \
  -d "url=https://example.com" \
  -d "category=ai"

通常はドキュメントで推奨されている X-API-Key を使えばよいと思います。


エラー時のレスポンス

パラメータが不足している場合などは、エラーがJSON形式で返されます。

例:

{
  "status": "error",
  "message": "Category is required."
}

APIドキュメントでは、以下のHTTPステータスが案内されています。

HTTP Status 内容
400 Bad Request
401 Unauthorized
405 Method Not Allowed
500 Server Error

実装時は、HTTPステータスとレスポンス本文の両方を確認しておくと扱いやすくなります。


APIキーの扱いについて

一般的なAPI利用時の注意点として、APIキーを公開リポジトリや公開ページに直接書かないようにします。

特にブラウザで動くJavaScriptにAPIキーを直接埋め込むと、利用者からキーを確認できる状態になります。

そのため、本番環境では必要に応じてサーバー側からAPIを呼び出す構成を検討してください。

この記事のJavaScriptコードでは、APIの呼び出し方を分かりやすくするため、

const apiKey = "your_API_KEY";

としています。


まとめ

nly.kr のURL短縮APIでは、

POST https://nly.kr/api/shorten

に対して、

  • APIキー
  • 元URL
  • カテゴリ

を送信することで、短縮URLをJSON形式で取得できます。

curlだけでなく、JavaScriptやPython、PHPなどからも利用できるため、短縮URLの自動生成をアプリケーションに組み込みたい場合に使えます。

APIドキュメント:

Web上で直接URLを短縮したい場合はこちら:


※この記事では、筆者が運営している nly.kr のAPIを使用しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?