How to perform external api call when a content type item is published and send data to external api?

I’m fetching product from external api and populating product model with custom logic in controller and service

I have to edit product info and send back from where I fetched them previously

I used lifecycle , afterCreate and afterUpdate to make a external post api call and sending a request body on edit and save

But how i can make the same but when I’do publish action

I looked into doc there it mentioned we can use webhook but how to send data of item which i just published

@Aditya_Tarale The webhook will fetch all params just like lifecycle hooks does. You can create a new webhook from strapi admin with api route and place it inside any content type.

1 Like

@Shekhar Could you please give example reference of doc ?

First create a webhook from Strapi:

Then create a custom api in particular content type directory.

In /api/content-type/routes/content-type.js file:

    method: 'POST',
    path: '/your-api-name',
    handler: 'api::region.region.executeExternalApi',

and add the function inside /api/content-type/controllers/content-type.js file:

executeExternalApi(): async (ctx) => {
    let request = ctx.request.body;
    let data = request.entry;
    let header = ctx.request.header;

    ...write your logic here

This function will be triggered whenever any record is Published from any of the content type.

If you want your logic to be executed for particular model you can apply a condition logic using ctx.request.body.model === ‘contentType-name’.

Hope this information will be clear to you.

@Shekhar Hi

I have made step as above

i hit the localhost:1337/api/product-update from postman it work like a custom route

but it does not seems to work around the idea of what we are trying on click of publish button in any product in list

if you correct if any mistake in above

I have looked into my project and it seems to work when I click on Publish.
Have you checked it by removing the config object?

@Shekhar Which config object you are referring ?

The one you have added inside custom route…

config: {
    auth: false

Are you able to capture the data of published item and able to call external api in controller ?
I am not sure the webhook is calling my controller function

Yes. I am able to capture the published content in webhook api. This is how the request object will look like:

Please check the below details of my work:
Webhook Api:

Make sure your API status is Enable.

Custom route:

Custom controller function:

Do check your code again and test it.

@Shekhar, I got it running, as i said I’m not sure web-hook calling the route,

actually problem was i was trying to call http://localhost:1338/api/my-api-url

i replace with system IP it worked

thanks Shekhar :smile:

1 Like