The top-headlines Endpoint

We can use this endpoint to get the current top headlines. The base URI for this endpoint is https://newsapi.org/v2/top-headlines.

Query parameters

Parameters

Type

Description

country

string

This refers to the key of the country that the user wants to get headlines for. The possible options are listed in the appendix. This parameter cannot be used with the source parameter.

category

string

This refers to the category that the user wants to get headlines—for example, sports or technology. This parameter cannot be used with the source parameter.

sources

string

These are sources we want headlines from. Multiple sources are separated using commas. We will get these sources using the source endpoint. This parameter cannot be used with the country or category parameter.

q

string

These are the keywords to look for in the title and body of the article. It supports advanced search just like for the `everything` endpoint.

pageSize

int


The number of results to return per page. It is 100 by default.

page

int

This is used to get a specific page in the results. It is 1 by default.

We cannot call the top-headlines endpoint without any query parameter. It requires at least one query parameter.

Use cases

Use the top-headlines endpoint with a single query parameter

The code below shows how we can use the top-headlines endpoint with a single query parameter. Just like the previous lesson, we are using the sources query parameter and assigning it the id saved previously. Click the “Run” button to execute the code.

Press + to interact
import requests
import json
URL=('https://newsapi.org/v2/top-headlines?'
'sources={{sources}}'
)
header = {
'X-Api-Key': "{{API_KEY}}"
}
response = requests.request("GET", URL, headers=header).json()
print(json.dumps(response, indent=4))

We’ll get the description, title, url, author, publishedAt, content, id and name of the source, and urlToImage for all available headlines related to the U.S.

We can replace the query parameter in line 5 to search using other criteria.

Use the top-headlines endpoint with multiple query parameters

We can further filter the results we got in the first case by adding another query parameter. The code below shows how we can use multiple parameters with this endpoint. Click the “Run” button to get technology-related headlines for the US.

Press + to interact
import requests
import json
URL=('https://newsapi.org/v2/top-headlines?'
'country=us&'
'category=technology'
)
header = {
'X-Api-Key': "{{API_KEY}}"
}
response = requests.request("GET", URL, headers=header).json()
print(json.dumps(response, indent=4))

Remember, we can use even more parameters. All we need to do is separate them using &, just like we separated country and category in the code above.