Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
How can I retrieve an image url from an api call?

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:

NYT Best seller API JSON call

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Using https

The 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);
  });

Using node-fetch

As 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);
  }
})();

Expected output

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
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda