### GNews API Example Search Request Source: https://docs.gnews.io/index An example of a practical API call to the GNews API's search endpoint. This demonstrates how to query for articles related to 'Google', specifying language, maximum results, and including the API key. ```Bash https://gnews.io/api/v4/search?q=Google&lang=en&max=5&apikey=YOUR_API_KEY ``` -------------------------------- ### Install gnews-php-client SDK Source: https://docs.gnews.io/libraries Official PHP SDK for GNews API. Supports PSR-4 autoloading, integrates with Guzzle HTTP client, provides exception handling, and requires PHP 7.4+. Install via Composer. ```bash composer require gnews-io/gnews-io-php ``` -------------------------------- ### GNews API Request Pattern Source: https://docs.gnews.io/index This snippet shows the basic structure for making requests to the GNews API. It includes the base URL, endpoint, parameters, and the required API key. ```Bash https://gnews.io/api/v4/{endpoint}?{parameters}&apikey=YOUR_API_KEY ``` -------------------------------- ### Install gnews-io-js SDK Source: https://docs.gnews.io/libraries Official JavaScript SDK for GNews API. Features a promise-based API, built-in error handling, automatic request throttling, and TypeScript support. Install via npm. ```bash npm install @gnews-io/gnews-io-js ``` -------------------------------- ### Fetch Top Headlines with Bash and jq Source: https://docs.gnews.io/endpoints/top-headlines-endpoint Fetches top headlines using the gnews.io API in Bash. It uses `curl` to make the request and `jq` to parse the JSON response, extracting and printing the title and description of the first article. Requires `jq` to be installed. ```Bash #!/bin/bash apikey='API_KEY' category='general' url="https://gnews.io/api/v4/top-headlines?category=$category&lang=en&country=us&max=10&apikey=$apikey" data=$(curl -s $url) articles=$(echo $data | jq '.articles') articles_length=$(echo $articles | jq length) for((i = 0; i < $articles_length; i++)); do title=$(echo $articles | jq ".[${i}].title") echo"Title: $title" description=$(echo $articles | jq ".[${i}].description") echo"Description: $description" break done ``` -------------------------------- ### Fetch and Parse News Articles with Bash and jq Source: https://docs.gnews.io/endpoints/search-endpoint This Bash script utilizes `curl` to fetch data from the gnews.io API and `jq` to parse the JSON response. It iterates through the articles, extracting and printing their titles and descriptions. Make sure you have `jq` installed. ```bash # Please note that you must have the package jq: https://stedolan.github.io/jq/ #!/bin/bash # TODO: replace API_KEY with your API key. apikey='API_KEY' url="https://gnews.io/api/v4/search?q=example&lang=en&max=10&apikey=$apikey" data=$(curl -s $url) articles=$(echo $data | jq '.articles') articles_length=$(echo $articles | jq length) echo $articles_length for((i = 0; i < $articles_length; i++));do echo $i # articles[i].title title=$(echo $articles | jq ".[${i}].title") echo"Title: $title" # articles[i].description description=$(echo $articles | jq ".[${i}].description") echo"Description: $description" # You can replace {property} below with any of the article properties returned by the API. # articles[i].{property} # {property}=$(echo $articles | jq ".[${i}].{property}") # echo "${property}" # Delete this line to display all the articles returned by the request. Currently only the first article is displayed. break done ``` -------------------------------- ### GNews API 400 Bad Request Error Example Source: https://docs.gnews.io/error-handling Provides examples of JSON responses for a 400 Bad Request error, indicating issues with query parameters or syntax. This helps developers identify and correct malformed requests. ```JSON { "errors":{ "q":"The query is required." } } ``` ```JSON { "errors":{ "q":"The query has a syntax error (see https://docs.gnews.io/endpoints/search-endpoint#query-syntax)." } } ``` -------------------------------- ### Fetch and Parse News Articles with C# Source: https://docs.gnews.io/endpoints/search-endpoint This C# code snippet demonstrates how to fetch news articles from the gnews.io API using HttpClient. It deserializes the JSON response using Newtonsoft.Json and prints the title and description of each article. Ensure you have the Newtonsoft.Json package installed. ```csharp // https://www.newtonsoft.com/json // dotnet add package Newtonsoft.Json // This library will be used to parse the JSON data returned by the API. using Newtonsoft.Json; // TODO: replace API_KEY with your API key. const string API_KEY = "API_KEY"; const string URL = $"https://gnews.io/api/v4/search?q=example&lang=en&max=10&apikey={API_KEY}"; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(URL); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(responseBody); List
articles = data.Articles; for(int i = 0; i < articles.Count; i++) { // articles[i].title Console.WriteLine($"Title: {articles[i].Title}"); // articles[i].description Console.WriteLine($"Description: {articles[i].Description}"); // You can replace {property} below with any of the article properties returned by the API. // articles[i].{property} // Console.WriteLine($"{articles[i].{property}}"); // Note that {property} must be compliant with the definition of class Article. // Delete this line to display all the articles returned by the request. Currently only the first article is displayed. break; } class ApiResponse { publicint TotalArticles {get;set;} publicList
Articles {get;set;}=new List
(); } class Article { publicstring Id {get;set;}=""; publicstring Title {get;set;}=""; publicstring Description {get;set;}=""; publicstring Content {get;set;}=""; publicstring Url {get;set;}=""; publicstring Image {get;set;}=""; publicSource Source {get;set;}=new Source(); } class Source { publicstring Id {get;set;}=""; publicstring Name {get;set;}=""; publicstring Url {get;set;}=""; } ``` -------------------------------- ### GNews Search Endpoint HTTP Request Source: https://docs.gnews.io/endpoints/search-endpoint This snippet shows the basic HTTP GET request to the GNews Search Endpoint. It includes the base URL and a mandatory 'q' parameter for search keywords, along with an API key. ```HTTP GET https://gnews.io/api/v4/search?q=example&apikey=API_KEY ``` -------------------------------- ### GNews API Request with API Key Source: https://docs.gnews.io/authentication This example shows how to include your API key in the query string of an HTTP request to the GNews API. The API key is essential for authenticating your requests. ```HTTP https://gnews.io/api/v4/{endpoint}?apikey=API_KEY ``` -------------------------------- ### GNews API 429 Too Many Requests Error Example Source: https://docs.gnews.io/error-handling Illustrates the JSON response for a 429 Too Many Requests error, which occurs when rate limits are exceeded. It advises implementing throttling and delays. ```JSON { "errors":[ "This request was blocked because you made too many requests on the API in a short period of time." ] } ``` -------------------------------- ### GNews API 401 Unauthorized Error Example Source: https://docs.gnews.io/error-handling Shows the JSON response for a 401 Unauthorized error, typically due to an invalid or missing API key. This helps users troubleshoot authentication issues. ```JSON { "errors":[ "Your API key is invalid." ] } ``` -------------------------------- ### GNews API JSON Response Example Source: https://docs.gnews.io/json-response This snippet demonstrates the typical JSON structure returned by the GNews API, showcasing the 'totalArticles' count and an array of 'articles'. Each article object includes details like ID, title, description, content, URL, image, publication date, and source information. ```json { "totalArticles": 54904, "articles": [ { "id": "71b99c858e6a70f708b8bc4892834a44", "title": "Google's Pixel 7 and 7 Pro's design gets revealed even more with fresh crisp renders", "description": "Now we have a complete image of what the next Google flagship phones will look like. All that's left now is to welcome them during their October announcement!", "content": "Google's highly anticipated upcoming Pixel 7 series is just around the corner, scheduled to be announced on October 6, 2022, at 10 am EDT during the Made by Google event. Well, not that there is any lack of images showing the two new Google phones, b... [1419 chars]", "url": "https://www.phonearena.com/news/google-pixel-7-and-pro-design-revealed-even-more-fresh-renders_id142800", "image": "https://m-cdn.phonearena.com/images/article/142800-wide-two_1200/Googles-Pixel-7-and-7-Pros-design-gets-revealed-even-more-with-fresh-crisp-renders.jpg", "publishedAt": "2022-09-28T08:14:24Z", "source": { "id": "bdf99ac789962533519a03e81267024f", "name": "PhoneArena", "url": "https://www.phonearena.com" } } ] } ``` -------------------------------- ### GNews API 403 Forbidden Error Example Source: https://docs.gnews.io/error-handling Displays the JSON response for a 403 Forbidden error, indicating that the user has exceeded their daily quota. It suggests checking usage and potential plan upgrades. ```JSON { "errors":[ "You have reached your request limit for today, the next reset will be tomorrow at midnight UTC. If you need more requests, you can upgrade your subscription here: https://gnews.io/pricing" ] } ``` -------------------------------- ### Fetch and Parse News Articles with PHP Source: https://docs.gnews.io/endpoints/search-endpoint This PHP code snippet shows how to retrieve news articles from the gnews.io API using cURL. It decodes the JSON response and iterates through the articles, printing their titles and descriptions. Ensure cURL is enabled in your PHP installation. ```php // TODO: replace API_KEY with your API key. $apikey='API_KEY'; $url="https://gnews.io/api/v4/search?q=example&lang=en&max=10&apikey=$apikey"; $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $data=json_decode(curl_exec($ch),true); curl_close($ch); $articles=$data['articles']; for($i=0;$i(responseBody); List
articles = data.Articles; for(int i = 0; i < articles.Count; i++) { Console.WriteLine($"Title: {articles[i].Title}"); Console.WriteLine($"Description: {articles[i].Description}"); break; } class ApiResponse { public int TotalArticles { get; set; } public List
Articles { get; set; } = new List
(); } class Article { public string Id { get; set; } = ""; public string Title { get; set; } = ""; public string Description { get; set; } = ""; public string Content { get; set; } = ""; public string Url { get; set; } = ""; public string Image { get; set; } = ""; public Source Source { get; set; } = new Source(); } class Source { public string Id { get; set; } = ""; public string Name { get; set; } = ""; public string Url { get; set; } = ""; } ``` -------------------------------- ### Fetch Articles with GNews API (Python) Source: https://docs.gnews.io/endpoints/search-endpoint This Python code snippet shows how to retrieve articles from the GNews API using the 'urllib.request' and 'json' libraries. It details how to set the API key, create the search URL, and parse the JSON response to print article titles and descriptions. It implicitly uses the AND operator. ```Python # https://docs.python.org/3/library/json.html # This library will be used to parse the JSON data returned by the API. import json # https://docs.python.org/3/library/urllib.request.html#module-urllib.request # This library will be used to fetch the API. import urllib.request # TODO: replace API_KEY with your API key. apikey ="API_KEY" url =f"https://gnews.io/api/v4/search?q=example&lang=en&max=10&apikey={apikey}" with urllib.request.urlopen(url)as response: data = json.loads(response.read().decode("utf-8")) articles = data["articles"] for i inrange(len(articles)): # articles[i].title print(f"Title: {articles[i]['title']}") # articles[i].description print(f"Description: {articles[i]['description']}") # You can replace {property} below with any of the article properties returned by the API. # articles[i].{property} # print(f"{articles[i]['{property}']}") ``` -------------------------------- ### Fetch Top Headlines with Python Source: https://docs.gnews.io/endpoints/top-headlines-endpoint Fetches top headlines using the gnews.io API in Python. It makes an HTTP request, parses the JSON response, and prints the title and description of the first article. Requires the `urllib` and `json` modules. ```Python import urllib.request import json apikey ="API_KEY" category ="general" url = f"https://gnews.io/api/v4/top-headlines?category={category}&lang=en&country=us&max=10&apikey={apikey}" with urllib.request.urlopen(url) as response: data = json.loads(response.read().decode("utf-8")) articles = data["articles"] for i in range(len(articles)): print(f"Title: {articles[i]['title']}") print(f"Description: {articles[i]['description']}") break ``` -------------------------------- ### Fetch Top Headlines in JavaScript Source: https://docs.gnews.io/endpoints/top-headlines-endpoint This JavaScript code snippet demonstrates how to fetch top headlines from the gnews.io API using the fetch API. It shows how to construct the URL with parameters like category and API key, process the JSON response, and log article titles and descriptions. It includes a placeholder for the API key and a loop to iterate through articles. ```JavaScript apikey ='API_KEY'; category ='general'; url ='https://gnews.io/api/v4/top-headlines?category='+ category +'&lang=en&country=us&max=10&apikey='+ apikey; fetch(url) .then(function(response){ return response.json(); }) .then(function(data){ articles = data.articles; for(i =0; i < articles.length; i++){ // articles[i].title console.log("Title: "+ articles[i]['title']); // articles[i].description console.log("Description: "+ articles[i]['description']); // You can replace {property} below with any of the article properties returned by the API. // articles[i].{property} // console.log(articles[i]['{property}']); // Delete this line to display all the articles returned by the request. Currently only the first article is displayed. break; } }); ``` -------------------------------- ### Fetch Top Headlines in Python Source: https://docs.gnews.io/endpoints/top-headlines-endpoint This Python code snippet is set up to fetch top headlines from the gnews.io API. It imports the necessary libraries, `json` for parsing the response and `urllib.request` for making the HTTP request. The code is intended to be completed with the API call and data processing logic. ```Python # https://docs.python.org/3/library/json.html # This library will be used to parse the JSON data returned by the API. import json # https://docs.python.org/3/library/urllib.request.html#module-urllib.request # This library will be used to fetch the API. import urllib.request ``` -------------------------------- ### Fetch Top Headlines with PHP Source: https://docs.gnews.io/endpoints/top-headlines-endpoint Fetches top headlines using the gnews.io API in PHP. It uses cURL to make the HTTP request, decodes the JSON response, and prints the title and description of the first article. ```PHP ``` -------------------------------- ### GNews Search Query Syntax - Phrase Search Source: https://docs.gnews.io/endpoints/search-endpoint Demonstrates how to perform an exact phrase search using quotation marks within the 'q' parameter for the GNews Search Endpoint. This ensures results match the specific sequence of keywords. ```Text Example: Not Valid | Valid ---|--- Hello**!** | "Hello**!** " Left **-** Right | "Left **-** Right" Question**?** | "Question**?** " ``` -------------------------------- ### JavaScript Fetch API Error Handling Source: https://docs.gnews.io/error-handling Demonstrates a best practice for handling API errors in JavaScript using the Fetch API. It includes checking the response status and catching network or other errors. ```JavaScript fetch(url) .then(response=>{ if(!response.ok){ thrownewError(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data=>{ // Handle successful response }) .catch(error=>{ // Handle error console.error('API Error:', error); }); ``` -------------------------------- ### GNews API Error Response Formats Source: https://docs.gnews.io/error-handling Illustrates the JSON structure for API errors. The first format shows a general error message, while the second details errors related to specific attributes, such as invalid query parameters. ```JSON { "errors":[ "" ] } ``` ```JSON { "errors":{ "attribute":"" } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.