Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
# Reference: Python Requests Tutorial: Request Web Pages, Download Images, POST Data, Read JSON, and More
# https://www.youtube.com/watch?v=tb8gHvYlCFs&t=839s
import requests # to get/download the data from the news Api
import json # to decode the api response
"""
Class APIManager
Handles HTTP communication with the API that provide data for the news service
"""
class APIManager:
"""
Method: getNews
Sends a GET request via the requests library to the API
- Builds the dictionary with the request parameters (header + querystring)
- Sends the request with GET method to the API url (rapidapi.com)
- Decodes the json response in a dictionary and returns the fields of interest (title, body, url) of the news
"""
def getNews(self, category):
url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/search/NewsSearchAPI" # url of the api
# The parameters of the API request
# Reference: rapidapi.com
querystring = {
"q": f"{category}", # news request based on category
"pageNumber": "1", # n. of pages can be changed
"pageSize": "1", # size of the page should limit to paragraphs
"autoCorrect": "true", # spelling checker
"fromPublishedDate": "null", # initial date
"toPublishedDate": "null" # end date
}
headers = {
'x-rapidapi-key': "20c7edee10msh9b13ee9a5b2a529p1d3da9jsnbed33a1d0b94", # sending header
'x-rapidapi-host': "contextualwebsearch-websearch-v1.p.rapidapi.com" # hosting sender
}
# creating request
response = requests.request("GET", url, headers=headers, params=querystring)
responseText = response.text # reads the JSON response provided by API (found in the text field)
data = json.loads(responseText) # converts JSON response in a Python dictionary
# Extracts data from the "data" dictionary and returns them
title = data['value'][0]['title']
body = data['value'][0]['body']
url = data['value'][0]['url']
return title, body, url