Home > Enterprise >  Calling a 3rd party api through a cloud function in firebase with AXIOS POST
Calling a 3rd party api through a cloud function in firebase with AXIOS POST

Time:04-27

I am trying to make an api call with Axios POST upon the first user login on a website that uses some text and requires an api key. I did the basic initializing stuff like const functions = require('firebase-functions') and var axios = require('axios') above.

exports.addSummaryMessage = functi ons.auth.user().onCreate(async (user) => {

    const response = await axios.post(
        'https://example.com/stuff',
        {
            headers: {
                contentType: 'content/json',
                Authorization:
                    'Bearer APIKEY',
            },
            text: 'wooooww',
        }
    )

    await admin.firestore().collection('messages').add({
        name: 'Firebase Bot',
        profilePicUrl: '/images/firebase-logo.png', // Firebase logo
        text: JSON.stringify(response),
        timestamp: admin.firestore.FieldValue.serverTimestamp(),
    })
})

In my functions log I get messages like >addSummaryMessage Function execution took 231 ms. Finished with status: error

I can track the calls received from the api and it never registers or sends back an output. All of the CORS have request, response which I don't think I can get with functions.auth.user().onCreate() What's going wrong here? My API works in reqbin with this raw

POST /stuff
Authorization: Bearer APIKEY
Host: example.com
Accept: application/json
Content-Type: application/json
Content-Length: 30

{
  "text":"wooooww"
    
}

EDIT: Got it working with this text in the function:

    var data = {}
    var url =
        'https://example.com'
    var resp
    await axios
        .post(url, data, {
            headers: {
                contentType: 'content/json',
                Authorization:
                    'Bearer API Key',
            },
        })
        .then((res) => {
            resp = res.data.stuff

            admin.firestore().collection('messages').add({
                name: 'Firebase Bot',
                profilePicUrl: '/images/firebase-logo.png', // Firebase logo
                text: resp,
                timestamp: admin.firestore.FieldValue.serverTimestamp(),
            })
        })
        .catch((err) => {
            console.log(err)
        })

Edit 2 My api didnt need text to run and it was confusing me about how to pass text into the post through data this worked for me

    var userText = 'wow'
    var data = {}
    data['text'] = userText
    var url = ....

CodePudding user response:

It's difficult to be sure about the problem you encounter without more details. But you mention that the second code works.

In addition we can see that you are not correctly managing the life cycle of your Cloud Function: you don't return a Promise. This typically results in some erratic behavior: the Cloud Function sometimes works and sometimes not...

So the following should work (untested of course, since we don't know the API called via Axios):

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();   // <= This is important

exports.addSummaryMessage = functions.auth.user().onCreate(async (user) => {

    const response = await axios.post(
        'https://example.com/stuff',
        {
            headers: {
                contentType: 'content/json',
                Authorization:
                    'Bearer APIKEY',
            },
            text: 'wooooww',
        }
    )

    await admin.firestore().collection('messages').add({
        name: 'Firebase Bot',
        profilePicUrl: '/images/firebase-logo.png', // Firebase logo
        text: JSON.stringify(response),
        timestamp: admin.firestore.FieldValue.serverTimestamp(),
    })

    return null;   // <= This is important
})
  • Related