### Install newsapi-python Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Install the package using pip. ```bash python -m pip install newsapi-python ``` -------------------------------- ### Get Everything Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Use the get_everything method to search for articles related to a query. ```python api.get_everything(q='bitcoin') ``` -------------------------------- ### Get Sources Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Use the get_sources method to retrieve a list of available news sources. ```python api.get_sources() ``` -------------------------------- ### Get Everything Endpoint Source: https://github.com/mattlisiv/newsapi-python/blob/master/docs/source/examples.md Use get_everything() to search for articles across all news sources. You can specify search terms, sorting, and language. ```python api.get_everything("hurricane OR tornado", sort_by="relevancy", language="en") ``` ```python api.get_everything("(hurricane OR tornado) AND FEMA", sort_by="relevancy") ``` -------------------------------- ### Sources Endpoint Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Get a list of all news sources available. ```APIDOC ## GET /sources ### Description Retrieves a list of all the news sources available through the News API. This method corresponds to the News API's `/sources` endpoint. ### Method GET ### Endpoint `/v2/sources` ### Parameters #### Query Parameters - **language** (string) - Optional - The 2-letter ISO 639-1 language code of the articles (e.g., 'en', 'fr'). - **country** (string) - Optional - The 2-letter ISO 3166-1 alpha-2 country code of the articles (e.g., 'us', 'gb'). - **category** (string) - Optional - The category of sources (e.g., 'business', 'technology'). ### Request Example ```python # Example using the Python client api.get_sources(language='en', country='us') ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **sources** (array) - A list of source objects. - **id** (string) - The ID of the source. - **name** (string) - The name of the source. - **description** (string) - A description of the source. - **url** (string) - The URL to the source's website. - **category** (string) - The category of the source. - **language** (string) - The language of the source. - **country** (string) - The country of the source. ``` -------------------------------- ### Get Sources Endpoint Source: https://github.com/mattlisiv/newsapi-python/blob/master/docs/source/examples.md Use get_sources() to retrieve a list of available news sources. You can filter by category, country, and language. ```python api.get_sources() ``` ```python api.get_sources(category="technology") ``` ```python api.get_sources(country="ru") ``` ```python api.get_sources(category="health", country="us") ``` ```python api.get_sources(language="en", country="in") ``` -------------------------------- ### GET /top-headlines Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Fetches live top and breaking headlines for a country, specific category, single source, or multiple sources. Articles are sorted by the earliest date published first. Note: you cannot mix the `sources` parameter with `country` or `category` parameters. ```APIDOC ## GET /top-headlines ### Description Fetches live top and breaking headlines for a country, specific category, single source, or multiple sources. Articles are sorted by the earliest date published first. Note: you cannot mix the `sources` parameter with `country` or `category` parameters. ### Method GET ### Endpoint /v2/top-headlines ### Parameters #### Query Parameters - **q** (string) - Optional - Search keywords or phrases in the article title only. - **qintitle** (string) - Optional - Search keywords or phrases in the article title only. - **sources** (string) - Optional - A comma-separated string of news sources (e.g. bbc-news,cnn). Cannot be used with `country` or `category`. - **domains** (string) - Optional - A comma-separated string of domains (e.g. bbc.co.uk, bbc.com). - **exclude_domains** (string) - Optional - A comma-separated string of domains to exclude (e.g. bbc.com). - **from_param** (string or datetime or timestamp) - Optional - A date or datetime string in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ), or a Unix timestamp. Retrieves articles published on or after this date/time. - **to** (string or datetime or timestamp) - Optional - A date or datetime string in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ), or a Unix timestamp. Retrieves articles published before this date/time. - **language** (string) - Optional - The 2-letter ISO 639-1 language code of the articles (e.g. ar, de, en, es, fr, he, it, nl, no, pt, ru, sv, ud, zh). - **sort_by** (string) - Optional - The method by which to sort articles. Possible values: `relevancy`, `popularity`, `publishedAt`. - **page_size** (integer) - Optional - The number of results to return per page. Default: 20. Max: 100. - **page** (integer) - Optional - Use this to page through the results. Default: 1. - **country** (string) - Optional - The 2-letter ISO 3166-1 code of the country you want headlines from (e.g. ae, ar, at, au, be, bg, br, ca, ch, cn, co, cu, cz, de, eg, fr, gb, gr, hk, hu, id, ie, il, in, it, jp, kr, lt, lv, ma, mx, my, ng, nl, no, nz, ph, pl, pt, ro, rs, ru, sa, se, sg, si, sk, th, tr, tw, ua, us, ve, za). - **category** (string) - Optional - The category you want to get headlines for. Possible values: `business`, `entertainment`, `general`, `health`, `science`, `sports`, `technology`. ### Request Example ```python from newsapi import NewsApiClient api = NewsApiClient(api_key='your-api-key-here') # Get top headlines from a specific country headlines = api.get_top_headlines(country='us') # Search headlines by keyword headlines = api.get_top_headlines(q='bitcoin', language='en') # Filter by category headlines = api.get_top_headlines(category='technology', country='gb') # Get headlines from specific sources with pagination headlines = api.get_top_headlines( sources='bbc-news,cnn,abc-news', page_size=50, page=1 ) # Search keywords in title only headlines = api.get_top_headlines(qintitle='climate change', country='us') ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **totalResults** (integer) - The total number of results available. - **articles** (array) - A list of article objects. - **source** (object) - Contains the id and name of the source. - **id** (string) - The ID of the source. - **name** (string) - The name of the source. - **author** (string) - The author of the article. - **title** (string) - The title of the article. - **description** (string) - The description of the article. - **url** (string) - The URL of the article. - **urlToImage** (string) - The URL of the article's image. - **publishedAt** (string) - The publication date of the article in ISO 8601 format. - **content** (string) - The content of the article. #### Response Example ```json { "status": "ok", "totalResults": 38, "articles": [ { "source": {"id": "cnn", "name": "CNN"}, "author": "Author Name", "title": "Article Title", "description": "Article description.", "url": "https://www.cnn.com/article", "urlToImage": "https://example.com/image.jpg", "publishedAt": "2024-01-01T12:00:00Z", "content": "Article content..." } ] } ``` ``` -------------------------------- ### GET /sources Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Retrieves a list of available news sources, which can be filtered by category, language, and country. ```APIDOC ## GET /sources ### Description Retrieves a list of available news sources, which can be filtered by category, language, and country. ### Method GET ### Endpoint /v2/sources ### Parameters #### Query Parameters - **language** (string) - Optional - The 2-letter ISO 639-1 language code of the articles (e.g. ar, de, en, es, fr, he, it, nl, no, pt, ru, sv, ud, zh). - **country** (string) - Optional - The 2-letter ISO 3166-1 code of the country you want headlines from (e.g. ae, ar, at, au, be, bg, br, ca, ch, cn, co, cu, cz, de, eg, fr, gb, gr, hk, hu, id, ie, il, in, it, jp, kr, lt, lv, ma, mx, my, ng, nl, no, nz, ph, pl, pt, ro, rs, ru, sa, se, sg, si, sk, th, tr, tw, ua, us, ve, za). - **category** (string) - Optional - The category you want to get headlines for. Possible values: `business`, `entertainment`, `general`, `health`, `science`, `sports`, `technology`. ### Request Example ```python from newsapi import NewsApiClient api = NewsApiClient(api_key='your-api-key-here') # Get all sources sources = api.get_sources() # Filter sources by country and category sources = api.get_sources(country='us', category='technology') ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **sources** (array) - A list of source objects. - **id** (string) - The ID of the source. - **name** (string) - The name of the source. - **description** (string) - A description of the source. - **url** (string) - The URL of the source's website. - **category** (string) - The category of the source. - **language** (string) - The language of the source. - **country** (string) - The country of the source. #### Response Example ```json { "status": "ok", "sources": [ { "id": "abc-news", "name": "ABC News", "description": "...", "url": "https://abcnews.go.com", "category": "general", "language": "en", "country": "us" } ] } ``` ``` -------------------------------- ### GET /everything Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Searches through millions of articles from over 30,000 large and small news sources and blogs. Supports advanced query syntax, date filtering, domain restrictions, and multiple sort options. ```APIDOC ## GET /everything ### Description Searches through millions of articles from over 30,000 large and small news sources and blogs. Supports advanced query syntax, date filtering, domain restrictions, and multiple sort options. ### Method GET ### Endpoint /v2/everything ### Parameters #### Query Parameters - **q** (string) - Required - Search keywords or phrases. Boolean operators like AND, OR, NOT are supported. Use parentheses for grouping. - **qintitle** (string) - Optional - Search keywords or phrases in the article title only. - **sources** (string) - Optional - A comma-separated string of news sources (e.g. bbc-news,cnn). Cannot be used with `country` or `category`. - **domains** (string) - Optional - A comma-separated string of domains (e.g. bbc.co.uk, bbc.com). - **exclude_domains** (string) - Optional - A comma-separated string of domains to exclude (e.g. bbc.com). - **from_param** (string or datetime or timestamp) - Optional - A date or datetime string in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ), or a Unix timestamp. Retrieves articles published on or after this date/time. - **to** (string or datetime or timestamp) - Optional - A date or datetime string in ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ), or a Unix timestamp. Retrieves articles published before this date/time. - **language** (string) - Optional - The 2-letter ISO 639-1 language code of the articles (e.g. ar, de, en, es, fr, he, it, nl, no, pt, ru, sv, ud, zh). - **sort_by** (string) - Optional - The method by which to sort articles. Possible values: `relevancy`, `popularity`, `publishedAt`. Default: `publishedAt`. - **page_size** (integer) - Optional - The number of results to return per page. Default: 20. Max: 100. - **page** (integer) - Optional - Use this to page through the results. Default: 1. ### Request Example ```python from newsapi import NewsApiClient import datetime as dt api = NewsApiClient(api_key='your-api-key-here') # Basic keyword search results = api.get_everything(q='tesla') # Advanced query syntax with boolean operators results = api.get_everything( q='(cryptocurrency OR bitcoin) AND regulation', language='en', sort_by='relevancy' ) # Search within specific domains results = api.get_everything( q='artificial intelligence', domains='techcrunch.com,wired.com,theverge.com', sort_by='publishedAt' ) # Exclude certain domains from results results = api.get_everything( q='politics', exclude_domains='cnn.com,foxnews.com' ) # Date range filtering with datetime objects results = api.get_everything( q='hurricane', from_param=dt.date(2024, 1, 1), to=dt.date(2024, 1, 31), language='en' ) # Date filtering with ISO-8601 strings results = api.get_everything( q='earthquake', from_param='2024-01-01', to='2024-01-15T23:59:59' ) # Date filtering with Unix timestamp results = api.get_everything( q='market crash', from_param=1704067200, # Unix timestamp to=1706745600 ) # Filter by specific sources with pagination results = api.get_everything( sources='reuters,associated-press,bloomberg', page_size=100, page=2 ) # Search keywords in article title only results = api.get_everything( qintitle='breaking news', language='en', sort_by='publishedAt' ) ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **totalResults** (integer) - The total number of results available. - **articles** (array) - A list of article objects. - **source** (object) - Contains the id and name of the source. - **id** (string) - The ID of the source. - **name** (string) - The name of the source. - **author** (string) - The author of the article. - **title** (string) - The title of the article. - **description** (string) - The description of the article. - **url** (string) - The URL of the article. - **urlToImage** (string) - The URL of the article's image. - **publishedAt** (string) - The publication date of the article in ISO 8601 format. - **content** (string) - The content of the article. #### Response Example ```json { "status": "ok", "totalResults": 1500, "articles": [ { "source": {"id": "reuters", "name": "Reuters"}, "author": "Author Name", "title": "Article Title", "description": "Article description.", "url": "https://www.reuters.com/article", "urlToImage": "https://example.com/image.jpg", "publishedAt": "2024-01-01T12:00:00Z", "content": "Article content..." } ] } ``` ``` -------------------------------- ### Get Top Headlines Source: https://github.com/mattlisiv/newsapi-python/blob/master/docs/source/examples.md Use get_top_headlines() to retrieve top news articles. You can filter by query, category, sources, and page size. ```python api.get_top_headlines() ``` ```python api.get_top_headlines(q="hurricane") ``` ```python api.get_top_headlines(category="sports") ``` ```python api.get_top_headlines(sources="abc-news,ars-technica", page_size=50) ``` -------------------------------- ### Fix UnicodeEncodeError on Windows Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Install and run 'win-unicode-console' to resolve Unicode encoding issues when printing JSON objects to the Windows command line. ```bash py -mpip install win-unicode-console ``` ```bash py -mrun myPythonScript.py ``` -------------------------------- ### Initialize NewsApiClient Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Initialize the client with your News API key. ```python api = NewsApiClient(api_key='XXXXXXXXXXXXXXXXXXXXXXX') ``` -------------------------------- ### News API Client Initialization Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Initialize the NewsApiClient with your API key. ```APIDOC ## Initialize NewsApiClient ### Description Instantiate the `NewsApiClient` class by providing your unique API key. ### Usage ```python from newsapi import NewsApiClient # Initialize the client with your API key api = NewsApiClient(api_key='YOUR_API_KEY') ``` ### Parameters - **api_key** (string) - Required - Your News API key. ``` -------------------------------- ### Initialize NewsApiClient Source: https://github.com/mattlisiv/newsapi-python/blob/master/docs/source/examples.md Initialize the NewsApiClient with your API key. The API key is required for all requests. You can also pass a persistent session object. ```python import os from newsapi import NewsApiClient # An API key; for example: "74f9e72a4bfd4dbaa0cbac8e9a17d34a" key = os.environ["news_api_secret"] api = NewsApiClient(api_key=key) ``` -------------------------------- ### NewsApiClient Initialization Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Initialize the NewsApiClient with your API key. You can also provide a custom requests.Session object for connection pooling. ```APIDOC ## NewsApiClient Initialization ### NewsApiClient The main client class for interacting with all News API endpoints. Requires an API key obtained from newsapi.org registration. ```python from newsapi import NewsApiClient # Basic initialization with API key api = NewsApiClient(api_key='your-api-key-here') # With a custom session for connection pooling import requests with requests.Session() as session: api = NewsApiClient(api_key='your-api-key-here', session=session) # Make multiple requests using the same TCP connection headlines = api.get_top_headlines(country='us') tech_news = api.get_everything(q='artificial intelligence') ``` ``` -------------------------------- ### Import NewsApiClient Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Import the client class into your Python project. ```python from newsapi import NewsApiClient ``` -------------------------------- ### Everything Endpoint Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Search through millions of articles from thousands of news sources. ```APIDOC ## GET /everything ### Description Searches through millions of articles from thousands of news sources. This method corresponds to the News API's `/everything` endpoint. ### Method GET ### Endpoint `/v2/everything` ### Parameters #### Query Parameters - **q** (string) - Required - Keywords or phrases to search for. - **searchIn** (string) - Optional - Search for the query in article titles, descriptions, or content (e.g., 'title,description'). - **sources** (string) - Optional - A comma-separated list of news sources (e.g., 'bbc-news', 'cnn'). - **domains** (string) - Optional - A comma-separated list of domains (e.g., 'bbc.com', 'cnn.com'). - **from** (string) - Optional - A date and optional time in ISO 8601 format (e.g., 'YYYY-MM-DD'). - **to** (string) - Optional - A date and optional time in ISO 8601 format (e.g., 'YYYY-MM-DD'). - **language** (string) - Optional - The 2-letter ISO 639-1 language code of the articles (e.g., 'en', 'fr'). - **sortBy** (string) - Optional - How to sort the articles ('relevancy', 'popularity', 'publishedAt'). - **pageSize** (integer) - Optional - The number of results to return per page. - **page** (integer) - Optional - The page number of results. ### Request Example ```python # Example using the Python client api.get_everything(q='bitcoin', language='en', sort_by='relevancy') ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **totalResults** (integer) - The total number of results available. - **articles** (array) - A list of article objects. - **source** (object) - Information about the news source. - **id** (string) - The ID of the source. - **name** (string) - The name of the source. - **author** (string) - The author of the article. - **title** (string) - The title of the article. - **description** (string) - A description of the article. - **url** (string) - The URL to the article. - **urlToImage** (string) - The URL to the article's image. - **publishedAt** (string) - The publication date and time of the article. - **content** (string) - The content of the article. ``` -------------------------------- ### Use Dedicated Session Source: https://github.com/mattlisiv/newsapi-python/blob/master/docs/source/examples.md Initialize NewsApiClient with a persistent requests.Session object for connection pooling and cookie persistence across multiple requests. Using a 'with' context manager ensures the session is closed. ```python import requests with requests.Session() as session: # Use a single session for multiple requests. Using a 'with' # context manager closes the session and TCP connection after use. api = NewsApiClient(api_key=key, session=session) data1 = api.get_top_headlines(category="technology") data2 = api.get_everything(q="facebook", domains="mashable.com,wired.com") ``` -------------------------------- ### Fetch News Sources with Filters Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Use get_sources() to retrieve news publishers. You can filter by category, country, and language. This is useful for discovering source IDs for other endpoints. ```python from newsapi import NewsApiClient api = NewsApiClient(api_key='your-api-key-here') # Get all available sources sources = api.get_sources() # Response: {'status': 'ok', 'sources': [{'id': 'abc-news', 'name': 'ABC News', ...}, ...]}) # Filter sources by category tech_sources = api.get_sources(category='technology') # Filter sources by country us_sources = api.get_sources(country='us') # Filter sources by language english_sources = api.get_sources(language='en') # Combine filters sources = api.get_sources( category='business', language='en', country='us' ) # Build a list of source IDs for use with other endpoints source_ids = ','.join([source['id'] for source in sources['sources']]) # Use with get_top_headlines headlines = api.get_top_headlines(sources=source_ids[:10]) # First 10 sources # Explore source details for source in sources['sources']: print(f"ID: {source['id']}") print(f"Name: {source['name']}") print(f"Description: {source['description']}") print(f"URL: {source['url']}") print(f"Category: {source['category']}") print(f"Language: {source['language']}") print(f"Country: {source['country']}") print("---") ``` -------------------------------- ### Error Handling with NewsAPIException Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Demonstrates how to handle errors returned by the NewsAPI, specifically using the custom NewsAPIException class to access detailed error information. ```APIDOC ## Error Handling ### NewsAPIException Custom exception class that captures API error responses including status, error code, and message details. ### Request Example ```python from newsapi import NewsApiClient from newsapi.newsapi_exception import NewsAPIException api = NewsApiClient(api_key='your-api-key-here') try: # This might fail due to invalid parameters or API limits results = api.get_everything(q='python programming') print(f"Found {results['totalResults']} articles") except NewsAPIException as e: # Access detailed error information print(f"Status: {e.get_status()}") # e.g., "error" print(f"Code: {e.get_code()}") # e.g., "apiKeyInvalid", "rateLimited" print(f"Message: {e.get_message()}") # Human-readable error message print(f"Full exception: {e.get_exception()}") except TypeError as e: # Parameter type validation errors print(f"Invalid parameter type: {e}") except ValueError as e: # Parameter value validation errors (invalid country, language, etc.) print(f"Invalid parameter value: {e}") ``` ### Response When a `NewsAPIException` is caught, you can access the following methods: - **get_status()**: Returns the status code of the error response (e.g., 'error'). - **get_code()**: Returns a specific error code (e.g., 'apiKeyInvalid', 'rateLimited'). - **get_message()**: Returns a human-readable error message. - **get_exception()**: Returns the full exception details. ``` -------------------------------- ### Constants Reference Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Provides a reference for allowed parameter values used across all NewsAPI endpoints, including countries, languages, categories, and sort methods. ```APIDOC ## Constants Reference ### Allowed Parameter Values Reference for valid parameter values used across all endpoints. ### Request Example ```python from newsapi import const # Supported countries (ISO 3166-1 codes) print(const.COUNTRIES) # {'ae', 'ar', 'at', 'au', 'be', 'bg', 'br', 'ca', 'ch', 'cn', 'co', 'cu', 'cz', # 'de', 'eg', 'fr', 'gb', 'gr', 'hk', 'hu', 'id', 'ie', 'il', 'in', 'it', 'jp', # 'kr', 'lt', 'lv', 'ma', 'mx', 'my', 'ng', 'nl', 'no', 'nz', 'ph', 'pl', 'pt', # 'ro', 'rs', 'ru', 'sa', 'se', 'sg', 'si', 'sk', 'th', 'tr', 'tw', 'ua', 'us', # 've', 'za'} # Supported languages (ISO-639-1 codes) print(const.LANGUAGES) # {'ar', 'de', 'en', 'es', 'fr', 'he', 'it', 'nl', 'no', 'pt', 'ru', 'sv', 'ud', 'zh'} # Supported categories print(const.CATEGORIES) # {'business', 'entertainment', 'general', 'health', 'science', 'sports', 'technology'} # Sort methods for get_everything() print(const.SORT_METHOD) # {'relevancy', 'popularity', 'publishedAt'} # API endpoint URLs print(const.TOP_HEADLINES_URL) # https://newsapi.org/v2/top-headlines print(const.EVERYTHING_URL) # https://newsapi.org/v2/everything print(const.SOURCES_URL) # https://newsapi.org/v2/sources # Default language mapping per country print(const.DEFAULT_LANGUAGES['us']) # 'en' print(const.DEFAULT_LANGUAGES['de']) # 'de' print(const.DEFAULT_LANGUAGES['jp']) # 'ja' ``` ### Description This section lists constants provided by the `newsapi.const` module, which are useful for validating and constructing API requests. - **const.COUNTRIES**: A set of supported country codes. - **const.LANGUAGES**: A set of supported language codes. - **const.CATEGORIES**: A set of supported news categories. - **const.SORT_METHOD**: A set of supported sorting methods for the `get_everything` endpoint. - **const.TOP_HEADLINES_URL**: The base URL for the top headlines endpoint. - **const.EVERYTHING_URL**: The base URL for the everything endpoint. - **const.SOURCES_URL**: The base URL for the sources endpoint. - **const.DEFAULT_LANGUAGES**: A dictionary mapping country codes to their default language codes. ``` -------------------------------- ### Fetch Top Headlines Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Retrieve top headlines by country, category, or specific sources. You can also filter by keywords, language, and search within the title. Note that `sources` cannot be mixed with `country` or `category`. ```python from newsapi import NewsApiClient api = NewsApiClient(api_key='your-api-key-here') # Get top headlines from a specific country headlines = api.get_top_headlines(country='us') # Response: {'status': 'ok', 'totalResults': 38, 'articles': [...] # Search headlines by keyword headlines = api.get_top_headlines(q='bitcoin', language='en') # Filter by category (business, entertainment, general, health, science, sports, technology) headlines = api.get_top_headlines(category='technology', country='gb') # Get headlines from specific sources with pagination headlines = api.get_top_headlines( sources='bbc-news,cnn,abc-news', page_size=50, page=1 ) # Search keywords in title only headlines = api.get_top_headlines(qintitle='climate change', country='us') # Iterate through articles for article in headlines['articles']: print(f"Title: {article['title']}") print(f"Source: {article['source']['name']}") print(f"URL: {article['url']}") print(f"Published: {article['publishedAt']}") print("---") ``` -------------------------------- ### Fetching News Sources Source: https://context7.com/mattlisiv/newsapi-python/llms.txt This endpoint allows you to fetch a subset of news publishers that top-headlines are available from. It's useful for discovering source identifiers to use with other endpoints. You can filter sources by category, country, or language. ```APIDOC ## GET /v2/sources ### Description Fetches a list of available news sources. This can be used to discover source identifiers for use with other endpoints. ### Method GET ### Endpoint /v2/sources ### Parameters #### Query Parameters - **category** (string) - Optional - Filters sources by a specific category. Allowed values: 'business', 'entertainment', 'general', 'health', 'science', 'sports', 'technology'. - **language** (string) - Optional - Filters sources by a specific language. Allowed values: 'ar', 'de', 'en', 'es', 'fr', 'he', 'it', 'nl', 'no', 'pt', 'ru', 'sv', 'ud', 'zh'. - **country** (string) - Optional - Filters sources by a specific country. Allowed values are ISO 3166-1 codes (e.g., 'us', 'gb', 'de'). ### Request Example ```python from newsapi import NewsApiClient api = NewsApiClient(api_key='your-api-key-here') # Get all available sources sources = api.get_sources() # Filter sources by category tech_sources = api.get_sources(category='technology') # Filter sources by country us_sources = api.get_sources(country='us') # Filter sources by language english_sources = api.get_sources(language='en') # Combine filters sources = api.get_sources( category='business', language='en', country='us' ) ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **sources** (array) - A list of source objects, each containing: - **id** (string) - The unique identifier for the source. - **name** (string) - The name of the source. - **description** (string) - A brief description of the source. - **url** (string) - The URL of the source's website. - **category** (string) - The category the source belongs to. - **language** (string) - The primary language of the source's content. - **country** (string) - The country the source is based in. #### Response Example ```json { "status": "ok", "sources": [ { "id": "abc-news", "name": "ABC News", "description": "Australia's ABC news source. Read the latest news and breaking news from Australia and around the world.", "url": "https://abcnews.go.com", "category": "general", "language": "en", "country": "us" } // ... more sources ] } ``` ``` -------------------------------- ### Search Everything Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Perform comprehensive searches across millions of articles. Supports advanced boolean queries, domain filtering (include/exclude), date range filtering using various formats, and sorting by relevancy, popularity, or publication date. ```python from newsapi import NewsApiClient import datetime as dt api = NewsApiClient(api_key='your-api-key-here') # Basic keyword search results = api.get_everything(q='tesla') # Advanced query syntax with boolean operators results = api.get_everything( q='(cryptocurrency OR bitcoin) AND regulation', language='en', sort_by='relevancy' # Options: relevancy, popularity, publishedAt ) # Search within specific domains results = api.get_everything( q='artificial intelligence', domains='techcrunch.com,wired.com,theverge.com', sort_by='publishedAt' ) # Exclude certain domains from results results = api.get_everything( q='politics', exclude_domains='cnn.com,foxnews.com' ) # Date range filtering with datetime objects results = api.get_everything( q='hurricane', from_param=dt.date(2024, 1, 1), to=dt.date(2024, 1, 31), language='en' ) # Date filtering with ISO-8601 strings results = api.get_everything( q='earthquake', from_param='2024-01-01', to='2024-01-15T23:59:59' ) # Date filtering with Unix timestamp results = api.get_everything( q='market crash', from_param=1704067200, # Unix timestamp to=1706745600 ) # Filter by specific sources with pagination results = api.get_everything( sources='reuters,associated-press,bloomberg', page_size=100, page=2 ) # Search keywords in article title only results = api.get_everything( qintitle='breaking news', language='en', sort_by='publishedAt' ) # Process results print(f"Total results: {results['totalResults']}") for article in results['articles']: print(f"{article['publishedAt']}: {article['title']}") ``` -------------------------------- ### Access Allowed Parameter Values Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Utilize the 'const' module to access predefined lists and dictionaries of valid parameters for countries, languages, categories, sort methods, and API endpoints. This helps in constructing valid API requests. ```python from newsapi import const # Supported countries (ISO 3166-1 codes) print(const.COUNTRIES) # {'ae', 'ar', 'at', 'au', 'be', 'bg', 'br', 'ca', 'ch', 'cn', 'co', 'cu', 'cz', # 'de', 'eg', 'fr', 'gb', 'gr', 'hk', 'hu', 'id', 'ie', 'il', 'in', 'it', 'jp', # 'kr', 'lt', 'lv', 'ma', 'mx', 'my', 'ng', 'nl', 'no', 'nz', 'ph', 'pl', 'pt', # 'ro', 'rs', 'ru', 'sa', 'se', 'sg', 'si', 'sk', 'th', 'tr', 'tw', 'ua', 'us', # 've', 'za'} # Supported languages (ISO-639-1 codes) print(const.LANGUAGES) # {'ar', 'de', 'en', 'es', 'fr', 'he', 'it', 'nl', 'no', 'pt', 'ru', 'sv', 'ud', 'zh'} # Supported categories print(const.CATEGORIES) # {'business', 'entertainment', 'general', 'health', 'science', 'sports', 'technology'} # Sort methods for get_everything() print(const.SORT_METHOD) # {'relevancy', 'popularity', 'publishedAt'} # API endpoint URLs print(const.TOP_HEADLINES_URL) # https://newsapi.org/v2/top-headlines print(const.EVERYTHING_URL) # https://newsapi.org/v2/everything print(const.SOURCES_URL) # https://newsapi.org/v2/sources # Default language mapping per country print(const.DEFAULT_LANGUAGES['us']) # 'en' print(const.DEFAULT_LANGUAGES['de']) # 'de' print(const.DEFAULT_LANGUAGES['jp']) # 'ja' ``` -------------------------------- ### Date Inputs for get_everything Source: https://github.com/mattlisiv/newsapi-python/blob/master/docs/source/examples.md Constrain search results using the from_param and to parameters in get_everything(). Supports datetime.date, datetime.datetime, string formats ('YYYY-MM-DD' or 'YYYY-MM-DDTHH:MM:SS'), and Unix timestamps. ```python import datetime as dt api.get_everything( q="hurricane", from_param=dt.date(2019, 9, 1), to=dt.date(2019, 9, 3), ) ``` ```python api.get_everything( q="hurricane", from_param=dt.datetime(2019, 9, 1, hour=5), to=dt.datetime(2019, 9, 1, hour=15), ) ``` ```python api.get_everything( q="hurricane", from_param="2019-08-01", to="2019-09-15", ) ``` ```python api.get_everything( q="hurricane", from_param="2019-08-01", to="2019-09-15", ) ``` ```python api.get_everything( q="venezuela", from_param="2019-08-01T10:30:00", to="2019-09-15T14:00:00", ) ``` -------------------------------- ### Top Headlines Endpoint Source: https://github.com/mattlisiv/newsapi-python/blob/master/README.md Retrieve top headlines from specified sources. ```APIDOC ## GET /top-headlines ### Description Fetches top headlines from specified news sources. This method corresponds to the News API's `/top-headlines` endpoint. ### Method GET ### Endpoint `/v2/top-headlines` ### Parameters #### Query Parameters - **q** (string) - Optional - Keywords or phrases to search for. - **sources** (string) - Optional - A comma-separated list of news sources (e.g., 'bbc-news', 'cnn'). - **language** (string) - Optional - The 2-letter ISO 639-1 language code of the articles (e.g., 'en', 'fr'). - **country** (string) - Optional - The 2-letter ISO 3166-1 alpha-2 country code of the articles (e.g., 'us', 'gb'). - **category** (string) - Optional - The category of articles (e.g., 'business', 'technology'). - **pageSize** (integer) - Optional - The number of results to return per page. - **page** (integer) - Optional - The page number of results. ### Request Example ```python # Example using the Python client api.get_top_headlines(sources='bbc-news', language='en', country='us') ``` ### Response #### Success Response (200) - **status** (string) - The status of the response ('ok' or 'error'). - **totalResults** (integer) - The total number of results available. - **articles** (array) - A list of article objects. - **source** (object) - Information about the news source. - **id** (string) - The ID of the source. - **name** (string) - The name of the source. - **author** (string) - The author of the article. - **title** (string) - The title of the article. - **description** (string) - A description of the article. - **url** (string) - The URL to the article. - **urlToImage** (string) - The URL to the article's image. - **publishedAt** (string) - The publication date and time of the article. - **content** (string) - The content of the article. ``` -------------------------------- ### Handle NewsAPI Exceptions Source: https://context7.com/mattlisiv/newsapi-python/llms.txt Implement try-except blocks to catch NewsAPIException and other potential errors like TypeError or ValueError. This allows graceful handling of API errors, invalid parameters, or rate limiting. ```python from newsapi import NewsApiClient from newsapi.newsapi_exception import NewsAPIException api = NewsApiClient(api_key='your-api-key-here') try: # This might fail due to invalid parameters or API limits results = api.get_everything(q='python programming') print(f"Found {results['totalResults']} articles") except NewsAPIException as e: # Access detailed error information print(f"Status: {e.get_status()}") # e.g., "error" print(f"Code: {e.get_code()}") # e.g., "apiKeyInvalid", "rateLimited" print(f"Message: {e.get_message()}") # Human-readable error message print(f"Full exception: {e.get_exception()}") except TypeError as e: # Parameter type validation errors print(f"Invalid parameter type: {e}") except ValueError as e: # Parameter value validation errors (invalid country, language, etc.) print(f"Invalid parameter value: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.