I'm trying to get an image url from the NYT best sellers api and for the life of me I can't get it to work
Here is my code thus far, at the moment I'm just trying to console.log the url just to see it working before I implement it (I've omitted the API key but I do have it and it works)
When I run it in my browser the terminal returns the 200 https status code and the entire JSON file as a string before encountering "SyntaxError: Unexpected end of JSON input at JSON.parse () at IncomingMessage. (C:\Users\esmee\Desktop\project-bookworm\index.js:18:29) at IncomingMessage.emit (node:events:520:28) at IncomingMessage.Readable.read (node:internal/streams/readable:527:10) at flow (node:internal/streams/readable:1012:34) at resume_ (node:internal/streams/readable:993:3) at processTicksAndRejections (node:internal/process/task_queues:83:21)" and crashing
const express = require("express");const https = require("https");
const app = express();
app.get("/", function(req, res) {
const url = "https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=" https.get(url, function(response) {
console.log(response.statusCode);
response.on("data", function(data) {
const bookData = JSON.parse(data);
const book1url = bookData.results.books[0].book_image;
console.log(book1url);
})
}) res.send("Server is up and running"); })
app.listen(3000, function() { console.log("Server is running on port 3000."); })
Here is a screenshot of the JSON returned in the browser from the URL:
httpsThe problem with your code is that you try to parse on the data event but the data event only signals that a chunk of data has been received. So you need to concatenate all chunks of data together and only as soon as the end event is received, which signals all chunks of data have been received, you can parse the whole body.
import https from "https";
const options = {
headers: {
// tell API you are expecting a JSON returned in the body
"Accept": "application/json"
},
};
const url = "https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json";
https.get(url, options, (res) => {
let body = "";
// data is called multiple times and just a chunk of data is returned!
res.on("data", (chunk) => {
body += chunk;
});
// end signals that all data is returned => you can now parse
res.on("end", () => {
try {
const json = JSON.parse(body);
console.log(res.statusCode);
console.log(json);
if(res.statusCode !== 200){
// error handling here
console.log(json.fault.faultstring);
}
else {
// successful request -> log the body
console.log(json)
}
} catch (error) {
console.error(error.message);
}
});
})
.on("error", (error) => {
console.error(error.message);
});
node-fetchAs this whole construct using the https package is not very straigtforward many people use the node-fetch package which simplifies this and is Promise based.
import fetch from "node-fetch";
(async () => {
const options = {
headers: {
// tell API you are expecting a JSON returned in the body
Accept: "application/json",
},
};
const url =
"https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json";
try {
const resp = await fetch(url, options);
console.log(resp.status);
const body = await resp.json();
console.log(body);
if (!resp.ok) {
// status code other than 200-299
// some error handling here
// in this case log the error message returned from the API
console.log(body.fault.faultstring);
} else {
// successful request -> log the body
console.log(body)
}
} catch (error) {
console.error(error);
}
})();
Both versions should print the same output. If you do not provide an API key like I did this will be the output:
401
{
fault: {
faultstring: 'Failed to resolve API Key variable request.queryparam.api-key',
detail: { errorcode: 'steps.oauth.v2.FailedToResolveAPIKey' }
}
}
Failed to resolve API Key variable request.queryparam.api-key
It looks like the request is not returning a JSON output.
Since it is a GET request, you can open the URL directly in a browser and see what it returns.
May be post the output so that we get a better idea of what is going on.