接入教程
1. 访问PoetryDB GitHub页面查看文档
2. 使用GET请求调用API端点(如/author, /title)
3. 解析返回的JSON数据获取诗歌信息
4. 根据需要过滤或处理诗歌内容
使用Python获取随机诗歌
python
import requests
url = 'https://poetrydb.org/random'
response = requests.get(url)
if response.status_code == 200:
poetry_data = response.json()
print(f"Title: {poetry_data[0]['title']}")
print(f"Author: {poetry_data[0]['author']}")
print("Lines:")
for line in poetry_data[0]['lines']:
print(line)
else:
print(f"Error: {response.status_code}")
使用PHP搜索特定作者的诗作
php
<?php
$author = 'William Shakespeare';
$url = 'https://poetrydb.org/author/' . urlencode($author);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$poems = json_decode($response, true);
if (!empty($poems)) {
echo "Found " . count($poems) . " poems by " . $author . "\n";
foreach ($poems as $index => $poem) {
echo ($index + 1) . ". " . $poem['title'] . "\n";
}
} else {
echo "No poems found for " . $author . "\n";
}
} else {
echo "Request failed with code: " . $httpCode . "\n";
}
?>
使用JavaScript获取诗歌标题列表
javascript
async function fetchPoemTitles() {
try {
const response = await fetch('https://poetrydb.org/title');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const titles = data.titles || [];
console.log(`Total titles available: ${titles.length}`);
// Display first 10 titles as an example
titles.slice(0, 10).forEach((title, index) => {
console.log(`${index + 1}. ${title}`);
});
} catch (error) {
console.error('Failed to fetch poem titles:', error);
}
}
// Call the function
fetchPoemTitles();
常见问题
PoetryDB API需要API密钥吗?
不需要。PoetryDB是一个完全免费的公共API,无需注册、API密钥或身份验证即可使用。所有数据都通过开放端点提供。
API有速率限制吗?
PoetryDB目前没有官方的速率限制,但建议合理使用以避免服务器过载。对于高频或批量请求,请考虑缓存响应或限制请求频率。
API支持哪些数据格式?
PoetryDB主要返回JSON格式的数据。所有端点都默认接受并返回JSON,使其易于集成到各种应用程序和编程语言中。
Aitishiku.com