0

I had a small node server and I use the framework fastify.

In one of my routes, I want to get the data from a third party API.

I tried the following snippet:

fastify.route({
    method: 'GET',
    url: 'https://demo.api.com/api/v2/project/',
    handler: async function ({ params, body}, reply) {
        if (!body) return reply.send({ sucess: false })

        console.log('testing')
        console.log(body)

        return reply.send({ sucess: true })
    }
})

Unfortunately, I cannot call the URL by get because GET url's can only start with '/'.

How do i call a third pary api via fastify? do i need a extention?

Robert
  • 7,394
  • 40
  • 45
  • 64

2 Answers2

1

If you need to define a route (like http://localhost:3000/) that proxies another server you need to use fastify-http-proxy.

Or if you need to call another endpoint and manage the response, there is the fastify.inject() utility but it is designed for testing.

Anyway, I think the best approach is to use some HTTP client like got

const got = require('got') // npm install got

fastify.get('/my-endpoint', async function (request, reply) {
  const response = await got('sindresorhus.com')
  console.log(response.body)
  // DO SOMETHING WITH BODY
  return { sucess: true }
})
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
1

Proxy your http requests to another server, with fastify hooks.

here is the example in fastify-http-proxy

server.register(require('fastify-http-proxy'), {
  upstream: 'http://my-api.example.com',
  prefix: '/api', // optional
  http2: false // optional
})

https://github.com/fastify/fastify-http-proxy/blob/master/example.js

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
Mohammad Khalid
  • 111
  • 1
  • 4