ホームページ バックエンド開発 Python チュートリアル NewsDataHub API を使用したページネーションを理解する

NewsDataHub API を使用したページネーションを理解する

Dec 18, 2024 pm 08:18 PM

Understanding Pagination with NewsDataHub API

このガイドでは、NewsDataHub API を使用するときに結果をページ分割する方法について説明します。

NewsDataHub API は、RESTful API インターフェイスを通じてニュース データを提供するサービスです。カーソルベースのページネーションを実装して大規模なデータセットを効率的に処理し、開発者が管理可能なバッチでニュース記事を取得できるようにします。各応答には記事のセットが含まれており、各記事オブジェクトにはタイトル、説明、発行日、ソース、内容、キーワード、トピック、センチメント分析などの詳細が含まれています⁠。この API は、結果内のシームレスなナビゲーションにカーソル パラメーターを使用し、検索パラメーターやフィルター オプションなどの高度な機能に関する包括的なドキュメントを提供します。

ドキュメントについては、https://newsdatahub.com/docs をご覧ください

API は通常、単一のリクエストですべての結果を返すのは現実的ではないため、応答で限られた量のデータを返します。代わりに、データを個別のページまたはバッチに分割する技術であるページネーションを使用します。これにより、クライアントは一度に 1 ページを取得し、管理可能な結果のサブセットにアクセスできるようになります。

/news エンドポイントに最初のリクエストを行い、結果の最初のバッチを受信すると、応答の形式は次のようになります。

{
    "next_cursor": "VW93MzoqpzM0MzgzMQpqwDAwMDQ5LjA6MzA0NTM0Mjk1T0xHag==",
        "total_results": 910310,
        "per_page": 10,
        "data": [
            {
                "id": "4927167e-93f3-45d2-9c53-f1b8cdf2888f",
                "title": "Jail time for wage theft: New laws start January",
                "source_title": "Dynamic Business",
                "source_link": "https://dynamicbusiness.com",
                "article_link": "https://dynamicbusiness.com/topics/news/jail-time-for-wage-theft-new-laws-start-january.html",
                "keywords": [
                    "wage theft",
                    "criminalisation of wage theft",
                    "Australian businesses",
                    "payroll errors",
                    "underpayment laws"
                ],
                "topics": [
                    "law",
                    "employment",
                    "economy"
                ],
                "description": "Starting January 2025, deliberate wage theft will come with serious consequences for employers in Australia.",
                "pub_date": "2024-12-17T07:15:00",
                "creator": null,
                "content": "The criminalisation of wage theft from January 2025 will be a wake-up call for all Australian businesses. While deliberate underpayment has rightly drawn scrutiny, our research reveals that accidental payroll errors are alarmingly common, affecting nearly 60% of companies in the past two years. Matt Loop, VP and Head of Asia at Rippling Starting January 1, 2025, Australias workplace compliance landscape will change dramatically. Employers who deliberately underpay employees could face fines as high as AU. 25 million or up to 10 years in prison under new amendments to the Fair Work Act 2009 likely. Employers must act decisively to ensure compliance, as ignorance or unintentional errors wont shield them from civil or criminal consequences. Matt Loop, VP and Head of Asia at Rippling, says: The criminalisation of wage theft from January 2025 will be a wake-up call for all Australian businesses. While deliberate underpayment has rightly drawn scrutiny, our research reveals that accidental payroll errors are alarmingly common, affecting nearly 60% of companies in the past two years. Adding to the challenge, many SMEs still rely on fragmented, siloed systems to manage payroll. This not only complicates operations but significantly increases the risk of errors heightening the potential for non-compliance under the new laws. The urgency for businesses to modernise their approach cannot be overstated. Technology offers a practical solution, helping to streamline and automate processes, reduce human error, and ensure compliance. But this is about more than just avoiding penalties. Accurate and timely pay builds trust with employees, strengthens workplace morale, and fosters accountability. The message is clear: wage theft isnt just a financial risk anymoreits a criminal offense. Now is the time to ensure your business complies with Australias new workplace laws. Keep up to date with our stories on LinkedIn, Twitter, Facebook and Instagram.",
                "media_url": "https://backend.dynamicbusiness.com/wp-content/uploads/2024/12/db-3-4.jpg",
                "media_type": "image/jpeg",
                "media_description": null,
                "media_credit": null,
                "media_thumbnail": null,
                "language": "en",
                "sentiment": {
                    "pos": 0.083,
                    "neg": 0.12,
                    "neu": 0.796
                }
            },
        // more article objects
      ]
  }
ログイン後にコピー

JSON 応答の最初のプロパティである next_cursor に注目してください。 next_cursor の値は、結果の次のページの先頭を指します。次のリクエストを行うときは、次のようにカーソル クエリ パラメータを指定します:

https://api.newsdatahub.com/v1/news?cursor=VW93MzoqpzM0MzgzMQpqwDAwMDQ5LjA6MzA0NTM0Mjk1T0xHag==

結果のページネーションを試す最も簡単な方法は、Postman または同様のツールを使用することです。これは、Postman でカーソル値を使用して結果をページ分割する方法を示す短いビデオです。

https://youtu.be/G7kkTwCPtCE

next_cursor 値が null の場合、選択した条件で利用可能な結果の最後に到達したことを示します。

Python を使用した結果のページ分割

ここでは、Python を使用して NewsDataHub API の結果を通じて基本的なページネーションを設定する方法を説明します。

import requests

# Make sure to keep your API keys secure
# Use environment variables instead of hardcoding
API_KEY = 'your_api_key'
BASE_URL = 'https://api.newsdatahub.com/v1/news'

headers = {
    'X-Api-Key': API_KEY,
    'Accept': 'application/json',
    'User-Agent': 'Mozilla/5.0 Chrome/83.0.4103.97 Safari/537.36'
}

params = {}
cursor = None

# Limit to 5 pages to avoid rate limiting while demonstrating pagination

for _ in range(5):
    params['cursor'] = cursor

    try:
        response = requests.get(BASE_URL, headers=headers, params=params)
        response.raise_for_status()
        data = response.json()
    except (requests.HTTPError, ValueError) as e:
        print(f"There was an error when making the request: {e}")
        continue

    cursor = data.get('next_cursor')

    for article in data.get('data', []):
        print(article['title'])

    if cursor is None:
        print("No more results")
        break
ログイン後にコピー

インデックスベースのページネーション

一部の API は、インデックスベースのページネーションを使用して、結果を個別のチャンクに分割します。このアプローチでは、API はデータの特定のページを返します。これは本の目次に似ており、各ページ番号が特定のセクションを指します。

インデックスベースのページネーションは実装が簡単ですが、いくつかの欠点があります。リアルタイムの更新に苦労し、一貫性のない結果が生成される可能性があり、新しいページを取得するたびに以前のレコードを順次スキャンする必要があるため、データベースへの負担が大きくなります。

NewsDataHub API におけるカーソルベースのページネーションの基礎について説明しました。検索パラメータやフィルタリング オプションなどの高度な機能については、https://newsdatahub.com/docs で完全な API ドキュメントを参照してください。

以上がNewsDataHub API を使用したページネーションを理解するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか? 中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか? Apr 02, 2025 am 07:15 AM

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は? プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は? Apr 02, 2025 am 07:18 AM

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

Investing.comの反クローラーメカニズムをバイパスするニュースデータを取得する方法は? Investing.comの反クローラーメカニズムをバイパスするニュースデータを取得する方法は? Apr 02, 2025 am 07:03 AM

Investing.comの反クラウリング戦略を理解する多くの人々は、Investing.com(https://cn.investing.com/news/latest-news)からのニュースデータをクロールしようとします。

Python 3.6のロードピクルスファイルエラーmodulenotfounderror:ピクルスファイル「__builtin__」をロードした場合はどうすればよいですか? Python 3.6のロードピクルスファイルエラーmodulenotfounderror:ピクルスファイル「__builtin__」をロードした場合はどうすればよいですか? Apr 02, 2025 am 06:27 AM

Python 3.6のピクルスファイルの読み込みエラー:modulenotfounderror:nomodulenamed ...

Scapy Crawlerを使用するときにパイプラインファイルを書き込めない理由は何ですか? Scapy Crawlerを使用するときにパイプラインファイルを書き込めない理由は何ですか? Apr 02, 2025 am 06:45 AM

SCAPYクローラーを使用するときにパイプラインファイルを作成できない理由についての議論は、SCAPYクローラーを学習して永続的なデータストレージに使用するときに、パイプラインファイルに遭遇する可能性があります...

See all articles