📅  最后修改于: 2023-12-03 15:26:14.871000             🧑  作者: Mango
这是一个程序员可以使用的新闻头条API。API返回最新的新闻头条,包括标题、发布日期和链接。
GET https://newsapi.org/v2/top-headlines
| 参数 | 描述 |
| --- | --- |
| country
| 可选。希望从哪个国家检索新闻头条。默认为所有国家。 |
| category
| 可选。要检索的新闻类别。支持business、entertainment、general、health、science、sports和technology。默认为所有类别。 |
| apiKey
| 必需。您的API密钥以访问API。 |
API返回最新的新闻头条列表,每个条目包含以下属性:
title
:新闻头条的标题。publishedAt
:新闻头条的发布日期和时间。url
:新闻头条的链接。{
"status": "ok",
"totalResults": 20,
"articles": [
{
"title": "Apple unveils new MacBook Air with M1 chip",
"publishedAt": "2020-11-10T08:00:00Z",
"url": "https://www.apple.com/mac/"
},
{
"title": "Microsoft acquires GitHub",
"publishedAt": "2018-06-04T15:30:00Z",
"url": "https://news.microsoft.com/2018/06/04/microsoft-github-empowering-developers/"
}
// more articles
]
}
如果出现任何问题,API将返回以下错误响应:
{
"status": "error",
"code": "API_KEY_INVALID",
"message": "Your API key is invalid."
}
以下示例使用Python 3和requests库来获取并打印头条新闻:
import requests
url = "https://newsapi.org/v2/top-headlines"
params = {
"apiKey": "YOUR_API_KEY",
"country": "us",
"category": "technology"
}
response = requests.get(url, params=params)
if response.status_code == 200:
articles = response.json()["articles"]
for article in articles:
print(f"{article['title']}, published on {article['publishedAt']}. Read more at {article['url']}")
else:
print(f"An error occurred: {response.status_code} - {response.json()['message']}")
返回的markdown代码片段如下:
# 新闻头条
这是一个程序员可以使用的新闻头条API。API返回最新的新闻头条,包括标题、发布日期和链接。
## API Endpoint
`GET https://newsapi.org/v2/top-headlines`
## 请求参数
| 参数 | 描述 |
| --- | --- |
| `country` | **可选**。希望从哪个国家检索新闻头条。默认为所有国家。 |
| `category` | **可选**。要检索的新闻类别。支持business、entertainment、general、health、science、sports和technology。默认为所有类别。 |
| `apiKey` | **必需**。您的API密钥以访问API。 |
## API响应
API返回最新的新闻头条列表,每个条目包含以下属性:
- `title`:新闻头条的标题。
- `publishedAt`:新闻头条的发布日期和时间。
- `url`:新闻头条的链接。
```json
{
"status": "ok",
"totalResults": 20,
"articles": [
{
"title": "Apple unveils new MacBook Air with M1 chip",
"publishedAt": "2020-11-10T08:00:00Z",
"url": "https://www.apple.com/mac/"
},
{
"title": "Microsoft acquires GitHub",
"publishedAt": "2018-06-04T15:30:00Z",
"url": "https://news.microsoft.com/2018/06/04/microsoft-github-empowering-developers/"
}
// more articles
]
}
如果出现任何问题,API将返回以下错误响应:
{
"status": "error",
"code": "API_KEY_INVALID",
"message": "Your API key is invalid."
}
以下示例使用Python 3和requests库来获取并打印头条新闻:
import requests
url = "https://newsapi.org/v2/top-headlines"
params = {
"apiKey": "YOUR_API_KEY",
"country": "us",
"category": "technology"
}
response = requests.get(url, params=params)
if response.status_code == 200:
articles = response.json()["articles"]
for article in articles:
print(f"{article['title']}, published on {article['publishedAt']}. Read more at {article['url']}")
else:
print(f"An error occurred: {response.status_code} - {response.json()['message']}")