我开始学习 JSON,在我的整个旅程中,我在使用 API 时没有遇到过 API 密钥。我正在尝试使用 pexels API,可以在此处找到https://www.pexels.com/api/documentation/?language=javascript。我获得了一个 API 密钥,如何在 JSON 中使用它。我知道这是一个荒谬的问题,但我一直无法找出答案。感谢您的帮助。
如果您仔细阅读他们提供的文档,了解如何使用您的 API_KEY。
您可以在此处查看文档。
您必须在请求
API_KEY
中将 header
传递为 Authorization
。
curl -H "Authorization: YOUR_API_KEY" \
"https://api.pexels.com/v1/search?query=people"
JS
fetch("https://api.pexels.com/v1/search?query=people", {
headers: {
Authorization: 'YOUR_API_KEY'
})
.then(response => response.json())
.then(result => console.log(result))
.catch(err => console.log(err))
首先,我建议您在项目的根目录中创建一个名为 .env.local 的 env 文件
然后将密钥添加到此环境文件中
YOUR_API_KEY = '1232123123123123123' <== your key insted of these random numbers
然后你可以安全地使用你的密钥进行 fetch 调用,然后像这样获取一些 pexels endopint
export const getDataFromApi = async () => {
const res = await fetch(
ENDPOINT_URL,
{
headers: {
Authorization: API_KEY,
},
}
);
const responseJson = await res.json();
return responseJson.photos;
};
我用 Py 函数随机选取图像。
def get_image():
try:
URL="https://api.pexels.com/v1/search?query=dogs&orientation=landscape&per_page=50"
headers = {
'Authorization': '[KEY HERE]'
}
rnd = random.randint(0, 49)
response = requests.get(URL, headers=headers)
imageurl = response.json()["photos"][rnd]["src"]["large"]
return imageurl
except:
return "https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg"