×

C# (.Net) client library

How to use the News API with C# (.Net)

Use C#(.Net) client library to integrate News API into your C#(.Net)  application

/// 
/// Performs a Web search and return the results as a SearchResult.
/// Required Package: Unirest-API (https://www.nuget.org/packages/Unirest-API/)
/// 

public static void Test()
{
    //Replace the following string value with your valid X-RapidAPI-Key.
    string Your_X_RapidAPI_Key = "xxxxxxxxxxxxxxxxxxxxx";

    //The query parameters: (update according to your search query)
    string q = "Taylor%20Swift"; //the search query
    int pageNumber = 1; //the number of requested page
    int pageSize = 10; //the size of a page
    bool autoCorrect = true; //autoCorrectspelling
    bool safeSearch = false; //filter results for adult content

    //Perform the web request and get the response
    var response = Unirest.get(string.Format("https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?q={0}&;pageNumber={1}&p;pageSize={2}&;autoCorrect={3}&;safeSearch={4}", q, pageNumber, pageSize, autoCorrect, safeSearch))
    .header("X-RapidAPI-Key", Your_X_RapidAPI_Key)
    .asJson();

    //Get the ResponseBody as a JSON
    dynamic jsonBody = JsonConvert.DeserializeObject(response.Body);

    //Parse the results

    //Get the numer of items returned
    int totalCount = (int)jsonBody["totalCount"];

    //Get the list of most frequent searches related to the input search query
    List relatedSearch = JsonConvert.DeserializeObject>(jsonBody["relatedSearch"].ToString());

    //Go over each resulting item
    foreach (var webPage in jsonBody["value"])
    {
        //Get the web page metadata
        string url = webPage["url"].ToString();
        string title = webPage["title"].ToString();
        string description = webPage["description"].ToString();
        string keywords = webPage["keywords"].ToString();
        string provider = webPage["provider"]["name"].ToString();
        DateTime datePublished = DateTime.Parse(webPage["datePublished"].ToString());

        //Get the web page image (if exists)
        string imageUrl = webPage["image"]["url"].ToString(); 
        int imageHeight = (int)webPage["image"]["height"]; 
        int imageWidth = (int)webPage["image"]["width"]; 

        //Get the web page image thumbail (if exists)
        string thumbnail = webPage["image"]["thumbnail"].ToString(); 
        int thumbnailHeight = (int)webPage["image"]["thumbnailHeight"]; 
        int thumbnailidth = (int)webPage["image"]["thumbnailWidth"]; 

        //An example: Output the webpage url, title and published date:
        Console.WriteLine(string.Format("Url: {0}. Title: {1}. Published Date:{2}.",
        url,
        title,
        datePublished));
    }
}