In this tutorial you will learn how to make asynchronous calls to PTV Developer APIs. As an alternative to synchronous requests they are used for potentially long running requests.
Preconditions
- A PTV Developer account and API Key
- An IDE for the programming language of your choice
Start Calculation
First define a function to start your job at a PTV Developer API. A job is the representation of an asynchronous transaction. Instead of a synchronous request that stays idle until a response is being sent, the asynchronous request starts a background job running on the server.
Asynchronous methods in PTV Developer are POST operations that begin with 'start...' (e.g. 'startAndCreateReachableLocations' or 'startOptimization'). In this tutorial the asynchronous 'calculateReachableAreas' endpoint of the Routing API is used as an example.
const apiKey = "YOUR_API_KEY"
function asyncCall() {
fetch("https://api.myptv.com/routing/v1/reachable-areas?waypoint=49.0133618,8.4277972&profile=EUR_TRUCK_40T&horizons=100,200&horizonType=DISTANCE", {
method: "POST",
headers: { apiKey: apiKey, "Content-Type": "application/json" },
})
.then(response => response.json())
.then(result => pollStatus(result.id));
}
Poll the status
Now create a function to poll the status of your job. Please set a timeout appropriate to your expected job duration between each request.
async function pollStatus(id) {
await Sleep(0);
getStatus(id);
}
function Sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
Request the status of your job
This function requests the status of your job. The status will be either 'RUNNING', 'FINISHED' or 'FAILED'. 'pollStatus' will be called again, if your job still has the status 'RUNNING'.
The result of your job will be returned by this endpoint as soon as its finished. Some APIs may have separated endpoints for polling the job status and getting its result.
function getStatus(id) {
fetch("https://api.myptv.com/routing/v1/reachable-areas/" + id, {
method: "GET",
headers: { apiKey: apiKey },
})
.then(response => response.json())
.then(result => result.status == "RUNNING" ? pollStatus(id) : console.log(result));
}
Delete a job
If the resource of the job is no longer needed or you want to cancel a job, it can be deleted via another endpoint.
function deleteJob(id) {
fetch("https://api.myptv.com/routing/v1/reachable-areas/" + id, {
method: "DELETE",
headers: { apiKey: apiKey },
})
.then(response => response.json())
.then(result => console.log(result));
}