Search code examples
jqueryajaxapify

How to call Apify Google Search Scraper Task Using JQuery/Ajax?


I am learning to use apify/google-search-scraper through their API call. The document is given here.

I am bit confused with their documentation as I am new. Especially I need the help to configure the call. It

$.ajax({
   url : '',  
   method : "POST",
   contentType: "application/json; charset=utf-8",

   data : {   

   },
   success:function(response) {
     console.log(response.data); 
   } 

 });

url: what should I write here?

data : Should I pass parameters here?

Thanks in advance.


Solution

  • You need to use run task API endpoint to run it. You can use synchronous run same as asynchronous.

    If you want to run the endpoint using AJAX you can use:

    $.ajax({
       url : 'https://api.apify.com/v2/actor-tasks/<your task name>/runs?token=<your api token>',  
       method : 'POST',
       contentType: 'application/json; charset=utf-8',
       success:function(response) {
         console.log(response.data); // Actor run object
       } 
    
     });
    

    If you need to get data from task run as well you need to wait until it finishes. Then get data from default dataset using get dataset items API endpoint. The good thing is that you can use waitForFinish param in calling run and it waits for it finishes.

    const getItemsFromDataset = (datasetId) => {
        $.ajax({
           url : `https://api.apify.com/v2/datasets/${datasetId}/items?format=json`,  
           method : 'GET',
           contentType: 'application/json; charset=utf-8',
           success:function(response) {
             console.log(response); // Items from dataset
           } 
    
         });
    }
    
    $.ajax({
       url : 'https://api.apify.com/v2/actor-tasks/<your task name>/runs?token=<your api token>&waitForFinish=120',  
       method : 'POST',
       dataType: 'json',
       data : JSON.stringify ({
          "queries" : "query you want to"
       }),
       success:function(response) {
         console.log(response.data); // Actor run object
         getItemsFromDataset(response.data.defaultDatasetId) 
       } 
    
     });
    

    You need to finish error handling in examples.

    EDIT: Added queries param to override query you want to scrape.