Create a Job using the SDK API

Hi,
I’m trying to create a Job using the SDK API:

However, I’m not sure what parameters are needed as the documentation is a bit scarce.
Could you please share more details about how to use this function and maybe some code examples?
Thanks
Fulei

Hi @fzhou ,

Thank you for your question. Using the SDK API, you could use the following snippet to help you for the example of a download job that is executed through the API:

from viktor.api_v1 import API, Entity


def run_job(self, entity: Entity, method: str) -> Dict:
    compute_result = entity.compute(
        method_name=method,
        params=entity.last_saved_params
    )
    return compute_result

Although this method refers to a download job that I’ve created, it can do any type of Controller endpoint calculation. Inspect the dictionary to see how the data is returned.

Let me know if this is not clear.

1 Like

Slightly out of topic, but is this entity.compute method also possible to do using the REST API?

Hi @PanjiBrotoisworo ,

I believe so. I’m not sure whether this is entirely how one would do it, but here is my attempt:

    def run_job(self, entity_id, params, method: str):
        url = f"{self.host}/workspaces/{self.workspace_id}/entities/{entity_id}/jobs/"
        payload = json.dumps({
            "params": params,
            "method_name": method,
        })
        response = requests.request("POST", url, headers=self.headers, data=payload)
        job_result = response.json()
        for i in range(120):
            response = requests.request("GET", job_result['url'], headers=self.headers)
            result = response.json()
            print(result['status'])
            if result['status'] == 'success':
                return result
            elif result['status'] == 'failed':
                raise UserError(result['message'])
            sleep(1)
        else:
            raise UserError(result['message'])
1 Like

The docs for the REST API contain the following 2 sections that can be chained together to create and fetch a job:

  1. Create a Job | VIKTOR Documentation
  2. Get Job by Id | VIKTOR Documentation

I suggest that you add a small wait time in between the requests for checking the job status (like @mslootweg did with the sleep) , as you might hit a rate limit otherwise.