NAV Navbar
Logo
php python csharp java

Rank Tracker API

Rank Tracker API helps to find rankings of a website in the result pages of the search engines that were specified.

The data will look like:

The tasks setting is made by few clients streams. At the same time few other clients streams constantly request our service to pick completed tasks from queue.

It is the most simplified and widespread method of work with Rank Tracker API.

You also can receive results of completed tasks using task_id or we can send them by ourselves as soon as they are ready if you specify postback_url or pingback_url when setting a task.

The time of results delivery is less for those tasks which priority is high.

Setting Rank Tasks

Instead of ‘login’ and ‘password’ use your credentials from https://my.dataforseo.com/login

<?php
require('RestClient.php');
//You can download this file from here https://api.dataforseo.com/_examples/php/_php_RestClient.zip

try {
    //Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
    $client = new RestClient('https://api.dataforseo.com/', null, 'login', 'password');
} catch (RestClientException $e) {
    echo "\n";
    print "HTTP code: {$e->getHttpCode()}\n";
    print "Error code: {$e->getCode()}\n";
    print "Message: {$e->getMessage()}\n";
    print  $e->getTraceAsString();
    echo "\n";
    exit();
}


$post_array = array();

//for example, some data selection cycle for tasks
for ($i = 0; $i < 3; $i++) {

    // example #1 - the simplest one
    // you set only a website URL and a search engine URL.
    // This search engine URL string will be searched, compared to our internal parameters
    // and used as:
    // "se_id", "loc_id", "key_id" ( actual and fresh list can be found here: "se_id":
    // https://api.dataforseo.com/v2/cmn_se , "loc_id": https://api.dataforseo.com/v2/cmn_locations ) (see example #3 for details)
    // If a task was set successfully, this *_id will be returned in results: 'v2/rnk_tasks_post' so you can use it.
    // The setting of a task can fail, if you set not-existent search engine, for example.
    // Disadvantages: You cannot work with "map pack", "maps", "mobile"
    $my_unq_id = mt_rand(0,30000000); //your unique ID. We will return it with all results
    $post_array[$my_unq_id] = array(
    "priority" => 1,
    "site" => "dataforseo.com",
    "url" => "https://www.google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS"
    );

    // example #2 - will return results faster than #1, but is simpler than example #3
    // All parameters should be set in the text format.
    // All data will will be searched, compared to our internal parameters
    // and used as:
    // "se_id", "loc_id", "key_id" ( actual and fresh list can be found here: "se_id": https://api.dataforseo.com/v2/cmn_se ,
    // "loc_id": https://api.dataforseo.com/v2/cmn_locations )
    // If a task was set successfully, this *_id will be returned in results: 'v2/rnk_tasks_post' so you can use it.
    // The setting of a task can fail, if you set not-existent search engine, for example.
    // Disadvantages: The process of search and comparison of provided data to our internal parameters may take some time.
    $my_unq_id = mt_rand(0,30000000); //your unique ID. will be returned with all results
    $post_array[$my_unq_id] = array(
    "priority" => 1,
    "site" => "dataforseo.com",
    "se_name" => "google.co.uk",
    "se_language" => "English",
    "loc_name_canonical"=> "London,England,United Kingdom",
    "key" => mb_convert_encoding("seo data api", "UTF-8")
    );

    // example #3 - the fastest one. All parameters should be set in our internal format.
    // Actual and fresh list can be found here: "se_id": https://api.dataforseo.com/v2/cmn_se ,
    // "loc_id": https://api.dataforseo.com/v2/cmn_locations
    $my_unq_id = mt_rand(0,30000000); //your unique ID. We will return it with all results
    $post_array[$my_unq_id] = array(
    "priority" => 1,
    "site" => "dataforseo.com",
    "se_id" => 22,
    "loc_id" => 1006886,
    "key_id" => 62845222
    );

    //This example has a cycle of up to 3 elements, but in the case of large number of tasks - send up to 100 elements per POST request
    if (count($post_array) > 99) {
        try {
            // POST /v2/rnk_tasks_post/$data
            // $tasks_data must by array with key 'data'
            $task_post_result = $client->post('v2/rnk_tasks_post', array('data' => $post_array));
            print_r($task_post_result);

            //do something with post results

            $post_array = array();
        } catch (RestClientException $e) {
            echo "\n";
            print "HTTP code: {$e->getHttpCode()}\n";
            print "Error code: {$e->getCode()}\n";
            print "Message: {$e->getMessage()}\n";
            print  $e->getTraceAsString();
            echo "\n";
        }
    }
}

if (count($post_array) > 0) {
    try {
        // POST /v2/rnk_tasks_post/$data
        // $tasks_data must by array with key 'data'
        $task_post_result = $client->post('v2/rnk_tasks_post', array('data' => $post_array));
        print_r($task_post_result);

        //do something with post results

    } catch (RestClientException $e) {
        echo "\n";
        print "HTTP code: {$e->getHttpCode()}\n";
        print "Error code: {$e->getCode()}\n";
        print "Message: {$e->getMessage()}\n";
        print  $e->getTraceAsString();
        echo "\n";
    }
}

$client = null;
?>
from random import Random
from client import RestClient
#You can download this file from here https://api.dataforseo.com/_examples/python/_python_Client.zip

#Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
client = RestClient("login", "password")
rnd = Random()
post_data = dict()
post_data[rnd.randint(1, 30000000)] = dict(
    priority=1,
    site="ranksonic.com",
    url="https://www.google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS"
)
post_data[rnd.randint(1, 30000000)] = dict(
    priority=1,
    site="dataforseo.com",
    se_name="google.co.uk",
    se_language="English",
    loc_name_canonical="London,England,United Kingdom",
    key="seo data api"
)
post_data[rnd.randint(1, 30000000)] = dict(
    priority=1,
    site="dataforseo.com",
    se_id=22,
    loc_id=1006886,
    key_id=1095202
)

response = client.post("/v2/rnk_tasks_post", dict(data=post_data))
if response["status"] == "error":
    print("error. Code: %d Message: %s" % (response["error"]["code"], response["error"]["message"]))
else:
    print(response["results"])
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DataForSeoDemos
{
    public static partial class Demos
    {
        public static async Task rnk_tasks_post()
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://api.dataforseo.com/"),

                //Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
                DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("login:password"))) }
            };
            var rnd = new Random();
            var postObject = new Dictionary<int, object>
            {
                [rnd.Next(1, 30000000)] = new
                {
                    priority = 1,
                    site = "ranksonic.com",
                    url = "https://www.google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS"
                },
                [rnd.Next(1, 30000000)] = new
                {
                    priority = 1,
                    site = "dataforseo.com",
                    se_name = "google.co.uk",
                    se_language = "English",
                    loc_name_canonical = "London,England,United Kingdom",
                    key = "seo data api"
                },
                [rnd.Next(1, 30000000)] = new
                {
                    priority = 1,
                    site = "dataforseo.com",
                    se_id = 22,
                    loc_id = 1006886,
                    key_id = 62845222
                }
            };
            var taskPostResponse = await httpClient.PostAsync("v2/rnk_tasks_post", new StringContent(JsonConvert.SerializeObject(new { data = postObject })));
            var obj = JsonConvert.DeserializeObject<dynamic>(await taskPostResponse.Content.ReadAsStringAsync());
            if (obj.status == "error")
                Console.WriteLine($"error. Code: {obj.error.code} Message: {obj.error.message}");
            else
            {
                foreach (var result in obj.results)
                {
                    var taskState = ((IEnumerable<dynamic>)result).First();
                    if (taskState.status == "error")
                        Console.WriteLine($"Error in task with post_id {taskState.post_id}. Code: {taskState.error.code} Message: {taskState.error.message}");
                    Console.WriteLine(taskState);
                }
            }
        }
    }
}
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;

public class Demos {
    public static void rnk_tasks_post() throws URISyntaxException, JSONException, IOException {
        URI url = new URI("https://api.dataforseo.com/v2/rnk_tasks_post");
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        //Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
        String basicAuth = Base64.getEncoder().encodeToString(("login:password").getBytes("UTF-8"));

        Map<Integer, Map<String, Object>> postValues = new HashMap<>();

        Random rnd = new Random();
        Map<String, Object> postObj1 = new HashMap<>();
        postObj1.put("priority", 1);
        postObj1.put("site", "ranksonic.com");
        postObj1.put("url", "https://www.google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS");
        postValues.put(rnd.nextInt(30000000), postObj1);

        Map<String, Object> postObj2 = new HashMap<>();
        postObj2.put("priority", 1);
        postObj2.put("site", "dataforseo.com");
        postObj2.put("se_name", "google.co.uk");
        postObj2.put("se_language", "English");
        postObj2.put("loc_name_canonical", "London,England,United Kingdom");
        postObj2.put("key", "seo data api");
        postValues.put(rnd.nextInt(300000), postObj2);

        Map<String, Object> postObj3 = new HashMap<>();
        postObj3.put("priority", 1);
        postObj3.put("site", "dataforseo.com");
        postObj3.put("se_id", 22);
        postObj3.put("loc_id", 1006886);
        postObj3.put("key_id", 62845222);
        postValues.put(rnd.nextInt(30000000), postObj3);

        JSONObject json = new JSONObject().put("data", postValues);
        StringEntity input = new StringEntity(json.toString());
        input.setContentType("application/json");
        post.setHeader("Content-type", "application/json");
        //post.setHeader("Accept", "application/json");
        post.setHeader("Authorization", "Basic " + basicAuth);
        post.setEntity(input);
        HttpResponse taskPostResponse = client.execute(post);
        JSONObject taskPostObj = new JSONObject(EntityUtils.toString(taskPostResponse.getEntity()));

        if (taskPostObj.get("status").equals("error") && !taskPostObj.getJSONObject("error").isNull("code")) {
            JSONObject error = taskPostObj.getJSONObject("error");
            Iterator<String> keys = error.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                System.out.println("error. Code:" + taskPostObj.getJSONObject("error").get("code") + " Message:" + taskPostObj.getJSONObject("error").get("message"));
            }
        } else {
            JSONObject results = taskPostObj.getJSONObject("results");
            Iterator<String> jkeys = results.keys();
            while (jkeys.hasNext()) {
                String key = jkeys.next();
                String status = results.getJSONObject(key).get("status").toString();
                if (status.equals("error"))
                    System.out.println("Error in task with post_id " + results.getJSONObject(key).get("post_id") + ". Code: " + results.getJSONObject(key).getJSONObject("error").get("code") + " Message: " + results.getJSONObject(key).getJSONObject("error").get("message"));
                else {
                    System.out.println(results.getJSONObject(key).toString());
                }
            }
        }
    }
}

The above command returns JSON structured like this:

{
    "status": "ok",
    "results_time": "0.6490 sec.",
    "results_count": 3,
    "results": {
        "11913258": {
            "post_id": "11913258",
            "post_key": "seo data api",
            "post_site": "dataforseo.com",
            "task_id": 380342739,
            "se_id": 22,
            "loc_id": 1006886,
            "key_id": 62845222,
            "status": "ok"
        },
        "11913049": {
            "post_id": "11913049",
            "post_key": "seo data api",
            "post_site": "dataforseo.com",
            "task_id": 380342739,
            "se_id": 22,
            "loc_id": 1006886,
            "key_id": 62845222,
            "status": "ok"
        },
        "20469414": {
            "post_id": "20469414",
            "post_key": "seo data api",
            "post_site": "dataforseo.com",
            "task_id": 380342741,
            "se_id": 22,
            "loc_id": 1006886,
            "key_id": 62845222,
            "status": "ok"
        }
    }
}

When we were developing the mechanism of tasks setting we tried to foresee many variations for your convenience. That’s why the range of fields is wide even though some of them are optional. Because of such flexibility for tasks settings it may seem that the process is difficult, but the things are simpler than you think.

We are sure that you will be able to pick the way of task setting that fits you the most.

All POST data should be sent in the JSON format (UTF-8 encoding). The task setting is done using POST method when array of tasks is sent in data field. We recommend to set up to 100 tasks at a time. Such limit was set because of the variations of tasks settings that you will use. If you use the field url then the processing of each task will take more time. If you use our identifiers (se_id, loc_id, key_id) then the processing of tasks will be made faster and you can set more than 100 elements at a time.

Description of the fields for a task setting:

Name of a field Type Description
priority integer execution priority
optional field
can have such values:
1 - normal execution priority (set by default)
2 - high execution priority
site string a website domain which rankings should be searched for in the SERP
required field
you can use wildcard (‘*’) to specify the search mask in the SERP. But if you decide to use a wildcard and want to include subdomains to the search then you should also specify it using wildcard.
examples:
   “example.com” (standard search)
   “example.com/” (search of exact URL)
   “example.com/eng/*” (search example.com and URLs which start with ‘/eng/’ in the SERP, such as ‘example.com/eng/index.html’ and ‘example.com/eng/help/’ etc)
   “*.example.com/eng/*” (search example.com and all its subdomain with URLs which start with ‘/eng/’ in the SERP such as ‘m.example.com/eng/index.html’ and ‘m.example.com/eng/some_url/’ etc.)
url string direct URL of a search query
optional field
you can specify a direct URL and we will sort it out to the necessary fields. Such method is the most difficult for our API processing and you should exactly specify language and location in the URL. We don’t recommend to use this method.
example:
https://www.google.co.uk/search?q=%20rank%20tracker%20api&hl=en&gl=GB&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS
se_id integer search engine id
optional field, if you specify se_name
you must choose one of the fields se_id or se_name
the list of available search engines with their se_id you can get by separate request List of Search Engines
also, when the information about set task is returned you will get se_id
se_name string search engine domain
optional field if you specify se_id
you must choose one of the fields se_id or se_name
the list of available search engines with se_name you can get by separate request List of Search Engines
example: “google.co.uk”
se_language string search engine language
required field if se_id is not specified
the list of available search engines with their se_language you can get by separate request List of Search Engines
example: “English”
loc_id integer search engine location id
optional field if you specify loc_name_canonical
you must choose one of the fields loc_id or loc_name_canonical
the list of available locations of search engines with their loc_id you can receive by separate request List of Locations
when the information about set task is returned you will get loc_id
please notice that we use Google Geographical Targeting including such types of locations as Country State Region Municipality City, that’s why you can specify in the field loc_id appropriate Criteria ID
loc_name_canonical string full name of search engine location
optional field if you specify loc_id
you must choose one of the fields loc_id or loc_name_canonical
the list of available locations of search engines with their loc_name_canonical you can receive by separate request List of Locations
please notice that we use Google Geographical Targeting including such types of locations as Country State Region Municipality City, that’s why you can specify in the field loc_name_canonical approriate to Canonical Name
example: “London,England,United Kingdom”
key_id integer keyword id
optional field if you specify key
when you set a task for the first time you won’t be able to know this field. But if you plan to collect rankings for this keyword we recommend you to save key_id returned after the task was set and use this field in the future.
key string keyword
optional field if you specify key_id
UTF-8 encoding
all %## will be decoded (plus symbol ‘+’ will be decoded to a space character)
if you need to use the “%” symbol for your key, please specify it as “%25”.

if this field contains ‘allinanchor:’, ‘allintext:’, ‘allintitle:’, ‘allinurl:’, ‘define:’, ‘definition:’, ‘filetype:’, ‘id:’, ‘inanchor:’, ‘info:’, ‘intext:’, ‘intitle:’, ‘inurl:’, ‘link:’, ‘related:’, ‘site:’ then the charge per task will be multiplied by 10.
se_param_add string additional parameters of search query
optional field
for example, if you want to disable auto correction of misspelling in the search query for google, you can specify “&nfpr=1”
Get the list of available parameters and additional details here.
postback_url string return URL for sending task results
optional field
if you specify this URL there will be no need to pick up tasks using Get Rank Tasks Results. We will send a result of a completed task by POST request for URL as soon as a task is completed.
pingback_url string notification URL of a completed task
optional field
when a task is completed we will notify you by GET request sent to the URL you have specified
you can use string ‘$task_id’ as $task_id variable and ‘$post_id’ as $post_id variable. we will set necessary values before sending of a request. for example:
  http://your-server.com/pingscript?taskId=$task_id
  http://your-server.com/pingscript?taskId=$task_id&postId=$post_id

When setting tasks, you send tasks data in the array using data field. The index of the task in this array ($my_unq_id variable in examples) can be used at any time after that as the post_id field. It will be returned to you with all server responses as well as our unique task_id field. Thanks to such feature, you can use this field to associate the set tasks with identifiers at your system.

Here are some examples:

  1. There is an identifier at your system of a task that you set to collect data, let it be 100500. When you set the task you send it in the data array with 100500 index like here: "{"data":{"100500":{"priority":1,"site":"ranksonic.com","se_name":"google.co.uk","se_language":"English","loc_name_canonical":"London,England,United Kingdom","key":"online rank tracker"}}}"
    When you get a result of this task, 100500 will be returned in the post_id field, and you will be able to associate the received result with the task specified at your system.
  2. You want to associate other kinds of data at your system. For instance:
    • a keyword has id=1238 at your system,
    • a search engine id=43289,
    • a location id=97435,
    • a language id=2,
    • a user for whom you want to complete this task has id=9999.

    Since the index of a task in the data array can be specified as a string, you can create this index using any symbol as a delimiter that fits you most to send the information mentioned above as a post_id. For instance, let’s see how it will look like if we use # as a delimiter. The index that includes all necessary data will have this value 1238#43289#97435#2#9999. As a result, the request for setting of a task will look like this: "{"data":{"1238#43289#97435#2#9999":{"priority":1,"site":"ranksonic.com","se_name":"google.co.uk","se_language":"English","loc_name_canonical":"London,England,United Kingdom","key":"online rank tracker"}}}"
    When you get the result of this task, you will be able to put in order the string to get the values you need. It will make the integration with our service easier for you.

As a response of API server you will receive JSON array in the field results of which there will be an information appropriate to the set tasks.

Description of the fields in the results array:

Name of a field Type Description
status string general result
“ok” - successful
“error” - error
if status=“error”, then you can see more detailed information of array error error
error array informational array of error
only if status=“error”
the list of possible errors can be found below.
      code integer error code
      message string text description of an error
results_time string execution time, seconds
results_count string number of elements in the array of results results
results array results array of tasks setting
            task_id integer unique task identifier in our system(UInt64)
in the future you will be able to use it within 30 days to request results of this task any time.
            status string results of this task setting
“ok” - successful
“error” - error
if status=“error”, then you can see more detailed information of array error error
            error array informational array of error
only if status=“error”
the list of possible errors can be found below.
                  code integer error code
                  message string text description of an error
            post_id string index in the array received in a POST request
            post_site string site received in a POST request
            post_key string key received in a POST request
keyword is returned with decoded %## (plus symbol ‘+’ will be decoded to a space character)
            se_id integer search engine id
if status=“ok”, then this field will be always filled
You can use it for finding relations between your and our search engines.
            loc_id integer search engine location id
if status=“ok”, then this field will always be filled
You can use it for finding relations between your and our search engines.
            key_id integer keyword id in our system
if you plan to use this keyword in the future we recommend you to save this id and use it when you set a task as key_id

Possible errors codes

Error Code Meaning
404 “not found or not enough data: site” - you didn’t specify a website in the task
404 “not found or not enough data: search engine” - you’ve specified nonexistent se_id or a search engine wasn’t found by specified se_name
404 “not found or not enough data: location” - you’ve specified nonexistent loc_id or a location of a search engine wasn’t found by specified loc_name_canonical
404 “not enough data: keyword” - you didn’t specify a keyword in the task
501 “invalid ‘data’ field” - probably you haven’t passed data for the tasks in the field data. POST data should be represented as an array and added to the field data: array(‘data’ => $post_array_for_tasks)
501 “invalid data” - Data in the field data isn’t an array with the required structure.
500 “internal error” - some internal error. We did our best to not let this type of error ever happen.

Get Rank Tasks Results

Instead of ‘login’ and ‘password’ use your credentials from https://my.dataforseo.com/login

<?php
require('RestClient.php');
//You can download this file from here https://api.dataforseo.com/_examples/php/_php_RestClient.zip

try {
    //Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
    $client = new RestClient('https://api.dataforseo.com', null, 'login', 'password');
} catch (RestClientException $e) {
    echo "\n";
    print "HTTP code: {$e->getHttpCode()}\n";
    print "Error code: {$e->getCode()}\n";
    print "Message: {$e->getMessage()}\n";
    print  $e->getTraceAsString();
    echo "\n";
}

/*
#1 - get ALL ready results
recommended use of getting results:
run this script by cron with 10-60 streams, every minute with random delay 0-30 sec.
usleep(mt_rand(0,30000000));
*/
try {
    //GET /v2/rnk_tasks_get
    $task_get_result = $client->get('v2/rnk_tasks_get');
    print_r($task_get_result);

    //do something with results

} catch (RestClientException $e) {
    echo "\n";
    print "HTTP code: {$e->getHttpCode()}\n";
    print "Error code: {$e->getCode()}\n";
    print "Message: {$e->getMessage()}\n";
    print  $e->getTraceAsString();
    echo "\n";
}


/*
#2 - get one result by task_id
*/
try {

    // GET /api/v1/tasks_get/$task_id
    $task_get_result = $client->get('v2/rnk_tasks_get/123456789');
    print_r($task_get_result);

    //do something with result

} catch (RestClientException $e) {
    echo "\n";
    print "HTTP code: {$e->getHttpCode()}\n";
    print "Error code: {$e->getCode()}\n";
    print "Message: {$e->getMessage()}\n";
    print  $e->getTraceAsString();
    echo "\n";
}

$client = null;
?>
from client import RestClient
#You can download this file from here https://api.dataforseo.com/_examples/python/_python_Client.zip

#Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
client = RestClient("login", "password")
response = client.get("/v2/rnk_tasks_get")
if response["status"] == "error":
    print("error. Code: %d Message: %s" % (response["error"]["code"], response["error"]["message"]))
else:
    print(response["results"])
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DataForSeoDemos
{
    public static partial class Demos
    {
        public static async Task rnk_tasks_get()
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://api.dataforseo.com/"),

                //Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
                DefaultRequestHeaders = {Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("login:password")))}
            };

            var response = await httpClient.GetAsync("v2/rnk_tasks_get");
            var obj = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
            if (obj.status == "error")
                Console.WriteLine($"error. Code: {obj.error.code} Message: {obj.error.message}");
            else if (obj.results_count != 0)
            {
                foreach (var result in obj.results)
                {
                    var resultItem = ((IEnumerable<dynamic>) result).First();
                    Console.WriteLine(resultItem);
                }
            }
            else
                Console.WriteLine("no results");

            var taskid = 123456789;
            response = await httpClient.GetAsync($"v2/rnk_tasks_get/{taskid}");
            obj = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
            if (obj.status == "error")
                Console.WriteLine($"error. Code: {obj.error.code} Message: {obj.error.message}");
            else if (obj.results_count != 0)
            {
                foreach (var result in obj.results)
                {
                    var resultItem = ((IEnumerable<dynamic>)result).First();
                    Console.WriteLine(resultItem);
                }
            }
            else
                Console.WriteLine("no results");
        }
    }
}
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;

public class Demos {
    public static void rnk_task_get() throws JSONException, URISyntaxException, IOException {
        URI url = new URI("https://api.dataforseo.com/v2/rnk_tasks_get");
        HttpClient client;
        client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        //Instead of 'login' and 'password' use your credentials from https://my.dataforseo.com/login
        String basicAuth = Base64.getEncoder().encodeToString(("login:password").getBytes("UTF-8"));
        get.setHeader("Content-type", "application/json");
        get.setHeader("Authorization", "Basic " + basicAuth);
        HttpResponse taskGetResponse = client.execute(get);
        JSONObject taskGetObj = new JSONObject(EntityUtils.toString(taskGetResponse.getEntity()));

        if (taskGetObj.get("status") == "error") {
            JSONObject errorObj = taskGetObj.getJSONObject("error");
            System.out.println("error. Code: " + errorObj.get("code") + " Message: " + errorObj.get("message"));
        } else if (!taskGetObj.get("results_count").equals(0)) {
            JSONObject results = taskGetObj.getJSONObject("results");
            JSONArray organicResults = results.getJSONArray("organic");
            System.out.println("organic:");
            for (int i = 0; i < organicResults.length(); i++) {
                System.out.println(organicResults.getJSONObject(i).get("task_id"));
                System.out.println(organicResults.getJSONObject(i));
            }
            JSONArray paidResults = results.getJSONArray("paid");
            if (paidResults.length() != 0) {
                System.out.println("paid:");
                for (int i = 0; i < paidResults.length(); i++) {
                    System.out.println(paidResults.getJSONObject(i));
                }
            }
        } else {
            System.out.println("no results");
        }
    }
}

The above command returns JSON structured like this:

{
    "status": "ok",
    "results_time": "0.0549 sec.",
    "results_count": 3,
    "results": {
        "organic": [
            {
                "post_id": "11913258",
                "task_id": 380342739,
                "se_id": 22,
                "loc_id": 1006886,
                "key_id": 62845222,
                "post_key": "seo data api",
                "post_site": "dataforseo.com",
                "result_datetime": "2018-03-13 16:18:12 +02:00",
                "result_position": 3,
                "result_url": "https://dataforseo.com/",
                "result_title": "SEO software API ⓴⓲. API for agencies. Best SEO data API provider.",
                "result_snippet_extra": "",
                "result_snippet": "DataForSEO ➤➤➤ SEO Software API ➤➤➤ SEO API data Provider built for SEO-Software companies and agencies. ✓✓✓ Great Speed, Clear Stats, Simple Pricing. Try for free now!",
                "results_count": 11500000,
                "result_extra": "",
                "result_spell": "",
                "result_spell_type": "",
                "result_se_check_url": "https://google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&gws_rd=cr&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS"
            },
            {
                "post_id": "11913049",
                "task_id": 380342739,
                "se_id": 22,
                "loc_id": 1006886,
                "key_id": 62845222,
                "post_key": "seo data api",
                "post_site": "dataforseo.com",
                "result_datetime": "2018-03-13 16:18:12 +02:00",
                "result_position": 3,
                "result_url": "https://dataforseo.com/",
                "result_title": "SEO software API ⓴⓲. API for agencies. Best SEO data API provider.",
                "result_snippet_extra": "",
                "result_snippet": "DataForSEO ➤➤➤ SEO Software API ➤➤➤ SEO API data Provider built for SEO-Software companies and agencies. ✓✓✓ Great Speed, Clear Stats, Simple Pricing. Try for free now!",
                "results_count": 11500000,
                "result_extra": "",
                "result_spell": "",
                "result_spell_type": "",
                "result_se_check_url": "https://google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&gws_rd=cr&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS"
            },
            {
                "post_id": "20469414",
                "task_id": 380342739,
                "se_id": 22,
                "loc_id": 1006886,
                "key_id": 62845222,
                "post_key": "seo data api",
                "post_site": "dataforseo.com",
                "result_datetime": "2018-03-13 16:18:12 +02:00",
                "result_position": 3,
                "result_url": "https://dataforseo.com/",
                "result_title": "SEO software API ⓴⓲. API for agencies. Best SEO data API provider.",
                "result_snippet_extra": "",
                "result_snippet": "DataForSEO ➤➤➤ SEO Software API ➤➤➤ SEO API data Provider built for SEO-Software companies and agencies. ✓✓✓ Great Speed, Clear Stats, Simple Pricing. Try for free now!",
                "results_count": 11500000,
                "result_extra": "",
                "result_spell": "",
                "result_spell_type": "",
                "result_se_check_url": "https://google.co.uk/search?q=seo%20data%20api&hl=en&gl=GB&gws_rd=cr&uule=w+CAIQIFISCXXeIa8LoNhHEZkq1d1aOpZS"
            }
        ],
        "paid": [
        ]
    }
}

You can receive results in three different ways:

  1. GET https://api.dataforseo.com/v2/rnk_tasks_get
    you will receive all complete results that have not been picked up.
  2. GET https://api.dataforseo.com/v2/rnk_tasks_get/$task_id
    after you’ve set a task there will be unique identifier returned to you in the response of our service. It is specified in the field task_id. You will be able to use it within 30 days to pick the results of the task.
  3. When setting a task (Setting Rank Tasks) you’ve specified pingback_url or postback_url. As soon as the task is completed we will send GET request to the URL you’ve specified as pingback_url or POST request with its results to the URL you specified as postback_url when the task was set.

Description of the fields for a request setting:

Name of a field Type Description
task_id integer unique task identifier in our system(UInt64)
in the future you will be able to use it within 30 days to request results of this task any time.

You will receive array from the API server in the field results where you will find rank tracker results.

Description of the fields in the results array:

Name of a field Type Description
status string general result
“ok” - successful
“error” - error
if status=“error”, then you can see more detailed information of array error error
error array informational array of error
only if status=“error”
the list of possible errors can be found below.
      code integer error code
      message string text description of an error
results_time string execution time, seconds
results_count string number of elements in the array of results results
results array results array of tasks
      organic array results array of organic SERP
            task_id integer unique task identifier in our system(UInt64)
in the future you will be able to use it within 30 days to request results of this task any time.
            post_id string index in the array received in a POST array
            post_site string site received in a POST array
            post_key string keyreceived in a POST array
keyword is returned with decoded %## (plus symbol ‘+’ will be decoded to a space character)
            se_id integer search engine id
You can use it for finding relations between your and our search engines.
            loc_id integer search engine location id
You can use it for finding relations between your and our search engines.
            key_id integer keyword id in our system
if you plan to use this keyword in the future we recommend you to save this id and use it when you set a task as key_id
            result_position integer position in the SERP
            result_datetime string date and time when a result was received
in the format “year-month-date:minutes:GMT_difference_hours:GMT_difference_minutes”
for example: “2016-12-13 15:30:34 +02:00”
time zone specified at your profile settings is used
            result_url string relevant URL in the SERP
            result_title string snippet header in the SERP
            result_snippet_extra string additional snippet in the SERP
ratings, price, author, etc
            result_snippet string snippet in the SERP
            results_count integer total number of results in the SERP
            result_extra string additional elements in the SERP
you can see such items separated by commas: app, blog, books, carousel, definition_block, discussions, images, knowledge_graph, maps, news, patents, places, recipes, shopping, videos
            result_spell string auto correction of a search engine
if a search engine provided results for a keyword that was corrected, we will specify the keyword corrected by a search engine
            result_spell_type string type of auto correction
types of hints: did_you_mean, showing_results_for
            result_se_check_url string direct URL to search engine results
You can use it to make sure that we provide exact results
      paid array results array of paid SERP
It will be available in the future, for now all the data in this field will always have empty array.
            task_id integer unique task identifier in our system(UInt64)
in the future you will be able to use it within 30 days to request results of this task any time.
            post_id string index in the array received in a POST array
            post_site string site received in a POST array
            post_key string keyreceived in a POST array
keyword is returned with decoded %## (plus symbol ‘+’ will be decoded to a space character)
            se_id integer search engine id
You can use it for finding relations between your and our search engines.
            loc_id integer search engine location id
You can use it for finding relations between your and our search engines.
            key_id integer keyword id in our system
if you plan to use this keyword in the future we recommend you to save this id and use it when you set a task as key_id
            result_position integer position in the SERP
            result_datetime string date and time when a result was received
in the format “year-month-date:minutes:GMT_difference_hours:GMT_difference_minutes”
for example: “2016-12-13 15:30:34 +02:00”
time zone specified at your profile settings is used
            result_url string relevant URL in the SERP
            result_title string snippet header in the SERP
            result_snippet_extra string additional snippet in the SERP
ratings, price, author, etc
            result_snippet string snippet in the SERP
            results_count integer total number of results in the SERP
            result_extra string additional elements in the SERP
you can see such items separated by commas: app, blog, books, carousel, definition_block, discussions, images, knowledge_graph, maps, news, patents, places, recipes, shopping, videos
            result_spell string auto correction of a search engine
if a search engine provided results for a keyword that was corrected, we will specify the keyword corrected by a search engine
            result_spell_type string type of auto correction
types of hints: did_you_mean, showing_results_for
            result_se_check_url string direct URL to search engine results
You can use it to make sure that we provide exact results