Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Translate curl request to axios request for AWS lambda function

I’m trying to translate a curl request to an axios request as such:

Here is the curl request format:

curl -s -X POST \
  -d '{"version": "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea", "input": {"prompt": "sunset over a lake in the mountains"}' \
  -H "Authorization: Token 123123123123123123" \
  -H 'Content-Type: application/json' \
  https://api.replicate.com/v1/predictions

And here is how I translated it to an axios request:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try {
    const response = await axios.post(
      "https://api.replicate.com/v1/predictions",
      '{"version": "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea", "input": {"prompt": "sunset over a lake in the mountains"}',
      {
        headers: {
          Authorization: "Token 123123123123123123",
          "Content-Type": "application/json",
        },
      }
    );

    console.log("RESPONSE ----->", response);
  } catch (err) {
    console.info("ERROR---->", err);
  }

However, I keep receiving the following error:

ERROR----> [AxiosError: Request failed with status code 400] {
  code: 'ERR_BAD_REQUEST'

Is the code formatted properly?

Full error:

2022-07-04T15:14:47.902Z    d13a7d45-eb0b-4365-a721-f06f2f2fc968    INFO    ERROR----> [AxiosError: Request failed with status code 400] {
  code: 'ERR_BAD_REQUEST',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function] },
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      Authorization: 'Token 123123123',
      'User-Agent': 'axios/0.27.2',
      'Content-Length': 150
    },
    method: 'post',
    url: 'https://api.replicate.com/v1/predictions',
    data: '"{\\"version\\": \\"2e3975b1692cd6aecac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea\\", \\"input\\": {\\"prompt\\": \\"sunset over a lake in the mountains\\"}"'
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      prefinish: [Function: requestOnPrefinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: null,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'api.replicate.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.replicate.com',
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 6,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object],
      [Symbol(RequestTimeout)]: undefined
    },
    _header: 'POST /v1/predictions HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: application/json\r\n' +
      'Authorization: Token 123123123123123\r\n' +
      'User-Agent: axios/0.27.2\r\n' +
      'Content-Length: 150\r\n' +
      'Host: api.replicate.com\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: noopPendingOutput],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object],
      requests: {},
      sockets: [Object],
      freeSockets: {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/v1/predictions',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      headers: [Object],
      rawHeaders: [Array],
      trailers: {},
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 400,
      statusMessage: 'Bad Request',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://api.replicate.com/v1/predictions',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'api.replicate.com',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 150,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://api.replicate.com/v1/predictions',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      authorization: [Array],
      'user-agent': [Array],
      'content-length': [Array],
      host: [Array]
    }
  },
  response: {
    status: 400,
    statusText: 'Bad Request',
    headers: {
      date: 'Mon, 04 Jul 2022 15:14:47 GMT',
      'content-type': 'application/json',
      'content-length': '74',
      connection: 'close',
      allow: 'GET, POST, HEAD, OPTIONS',
      'x-frame-options': 'DENY',
      'x-content-type-options': 'nosniff',
      'referrer-policy': 'same-origin',
      'cross-origin-opener-policy': 'same-origin',
      via: '1.1 vegur',
      'cf-cache-status': 'DYNAMIC',
      'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
      'report-to': '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=BBZ%2FuLKvNnSPD5CiPhRgFwAJA2cjjQUj29MokMhPaNhdRqCr%2Fe4xMan2uLUk2YW3q10spY8wQPnRlmhFUfg6N5t4kLVwBqmKs2UD%2B8Q9Fx7v5zXNpoV%2FkTNRt352MjWtAmKV"}],"group":"cf-nel","max_age":604800}',
      nel: '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}',
      'strict-transport-security': 'max-age=15552000',
      server: 'cloudflare',
      'cf-ray': '7258d008fc19823f-IAD'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      env: [Object],
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'post',
      url: 'https://api.replicate.com/v1/predictions',
      data: '"{\\"version\\": \\"2e3975b1692cd6aecac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea\\", \\"input\\": {\\"prompt\\": \\"sunset over a lake in the mountains\\"}"'
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'POST /v1/predictions HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'Authorization: Token 123123123123123\r\n' +
        'User-Agent: axios/0.27.2\r\n' +
        'Content-Length: 150\r\n' +
        'Host: api.replicate.com\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/v1/predictions',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'api.replicate.com',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: { non_field_errors: [Array] }
  }
}

>Solution :

You are forgetting the Token part in the Authorization header:

Authorization: "123123123123123123"

If you look on the response from your axios call you will see this:

data: { detail: 'Authentication credentials were not provided.' }

So just update your code and add the Token:

Authorization: "Token 123123123123123123"

I also think you might have problem with you actual data, try sending it like this instead:

const response = await axios.post(
  "https://api.replicate.com/v1/predictions",
  {
    version: "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea",
    input: {
      prompt: "sunset over a lake in the mountains"
    }
  },
  {
    headers: {
      Authorization: "Token 123123123123123123",
      "Content-Type": "application/json",
    },
  }
);

or serialize the data before you send it:

const data = JSON.stringify({
    version: "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea",
    input: {
      prompt: "sunset over a lake in the mountains"
    }
});
const response = await axios.post(
  "https://api.replicate.com/v1/predictions", data,
  {
    headers: {
      Authorization: "Token 123123123123123123",
      "Content-Type": "application/json",
    },
  }
);

As you can see in your error message the data is getting escaped, so this is probably the problem:

data: '"{\\"version\\": \\"2e3975b1692cd6aecac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea\\", \\"input\\": {\\"prompt\\": \\"sunset over a lake in the mountains\\"}"'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading