Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PDFCLOUD-3551 Update API polling samples to get their own request IDs #68

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -1287,3 +1287,5 @@ FodyWeavers.xsd

Node/node_modules/
Node/package-lock.json
PHP/**/vendor/**
PHP/**/composer.*
92 changes: 84 additions & 8 deletions DotNET/Endpoint Examples/Multipart Payload/request-status.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,93 @@
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Linq;

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
/*
* This sample demonstrates how to send a polling API request in order to obtain a request
* status.
*/
public class PollableApiExample
{
string requestId = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // requestId to poll
using (var request = new HttpRequestMessage(HttpMethod.Get, "request-status" + requestId))
private const string ApiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Your API key here
private const string BaseUri = "https://api.pdfrest.com";

public static async Task Main(String[] args)
{
request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
const string pathToFile = "/path/to/file.pdf"; // Path to the input file here
const string fileName = "file.pdf"; // Name of the file here

var response = await httpClient.SendAsync(request);
// Send a request with the 'response-type' header.
string bmpResponse = await GetBmpResponseAsync(pathToFile, fileName);
dynamic bmpResponseJson = JObject.Parse(bmpResponse);
if (bmpResponseJson.ContainsKey("error"))
{
Console.WriteLine($"Error from initial request: {bmpResponseJson.error}");
} else
{
// Get the request ID from the response.
string requestId = bmpResponseJson.requestId;
Console.WriteLine($"Received request ID: {requestId}");

// Use the request ID to send a polling request.
string requestStatusResponse = await GetRequestStatusAsync(requestId);
dynamic requestStatusResponseJson = JObject.Parse(requestStatusResponse);

// If the request is still pending, send another call momentarily.
while (requestStatusResponseJson.status == "pending")
{
const int delay = 5; // (seconds)
Console.WriteLine($"Response from /request-status for request {requestId}: {requestStatusResponseJson}");
Console.WriteLine($"Request status was \"pending\". Checking again in {delay} seconds...");
await Task.Delay(TimeSpan.FromSeconds(delay));
requestStatusResponse = await GetRequestStatusAsync(requestId);
requestStatusResponseJson = JObject.Parse(requestStatusResponse);
}
// The request status is no longer "pending".
Console.WriteLine($"Response from /request-status: {requestStatusResponseJson}");
Console.WriteLine("Done!");
}
}

/*
* Send a request with the 'response-type' header to get a request ID. /bmp is an arbitrary example.
*/
public static async Task<string> GetBmpResponseAsync(string pathToFile, string fileName)
{
using var httpClient = new HttpClient { BaseAddress = new Uri(BaseUri) };

using var bmpRequest = new HttpRequestMessage(HttpMethod.Post, "bmp");

bmpRequest.Headers.TryAddWithoutValidation("Api-Key", ApiKey);

var apiResult = await response.Content.ReadAsStringAsync();
bmpRequest.Headers.Accept.Add(new("application/json"));
var multipartContent = new MultipartFormDataContent();

var byteArray = File.ReadAllBytes(pathToFile);
var byteAryContent = new ByteArrayContent(byteArray);
multipartContent.Add(byteAryContent, "file", fileName);
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");

// By adding the 'response-type' header to the request, the response will include a 'status' key.
bmpRequest.Headers.Add("response-type", "requestId");

bmpRequest.Content = multipartContent;
Console.WriteLine("Sending request to /bmp...");
var bmpResponse = await httpClient.SendAsync(bmpRequest);

return await bmpResponse.Content.ReadAsStringAsync();
}

/*
* Get the request status from /request-status using the given request ID.
*/
public static async Task<string> GetRequestStatusAsync(string requestId)
{
using var httpClient = new HttpClient { BaseAddress = new Uri(BaseUri) };
using var request = new HttpRequestMessage(HttpMethod.Get, $"request-status/{requestId}");
request.Headers.TryAddWithoutValidation("Api-Key", ApiKey);

var response = await httpClient.SendAsync(request);

Console.WriteLine("API response received.");
Console.WriteLine(apiResult);
return await response.Content.ReadAsStringAsync();
}
}
89 changes: 73 additions & 16 deletions Java/Endpoint Examples/Multipart Payload/RequestStatus.java
Original file line number Diff line number Diff line change
@@ -1,43 +1,100 @@
import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.*;
import org.json.JSONObject;

public class RequestStatus {

// Request UUIDs can be found in the JSON response of POST requests as "requestId" when API
// Polling is enabled.
// Resource UUIDs usually look like this: '0950b9bdf-0465-4d3f-8ea3-d2894f1ae839'.
private static final String REQUEST_ID =
"2e3c603d1-30b2-4c16-8c11-911a51bb2ba9"; // place requestID here

// Specify your API key here, or in the environment variable PDFREST_API_KEY.
// You can also put the environment variable in a .env file.
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
// Specify the path to your file here, or as the first argument when running the program.
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";

public static void main(String[] args) {

File inputFile;
if (args.length > 0) {
inputFile = new File(args[0]);
} else {
inputFile = new File(DEFAULT_FILE_PATH);
}

final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
String apiKey = dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY);

String urlString = String.format("https://api.pdfrest.com/request-status/%s", REQUEST_ID);
// Using PDF/A as an arbitrary example, send a request with a 'response-type' header.
String pdfaResponse = getPdfaResponse(inputFile, apiKey);
JSONObject pdfaJson = new JSONObject(pdfaResponse);
if (pdfaJson.has("error")) {
System.out.println("Error during PDFA call: " + pdfaJson.getString("error"));
} else {
// Get a request ID from the response.
String requestID = pdfaJson.getString("requestId");

// Check the request status.
String requestStatusResponse = getRequestStatusResponse(requestID, apiKey);
JSONObject requestStatusJson = new JSONObject(requestStatusResponse);

// If still pending, check periodically for updates.
while (requestStatusJson.getString("status").equals("pending")) {
final int delay = 5000;
try {
Thread.sleep(delay);
requestStatusResponse = getRequestStatusResponse(requestID, apiKey);
requestStatusJson = new JSONObject(requestStatusResponse);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

private static String getPdfaResponse(File inputFile, String apiKey) {

final RequestBody inputFileRequestBody =
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody =
new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
.addFormDataPart("output_type", "PDF/A-2u")
.addFormDataPart("output", "pdfrest_pdfa")
.build();
Request request =
new Request.Builder()
.header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
.url(urlString)
.get()
.header("Api-Key", apiKey)
.header("response-type", "requestId")
.url("https://api.pdfrest.com/pdfa")
.post(requestBody)
.build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();

Response response = client.newCall(request).execute();
System.out.println("Result code " + response.code());
String responseBody = response.body().string();
System.out.println(prettyJson(responseBody));
return responseBody;
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private static String getRequestStatusResponse(String requestId, String apiKey) {
String urlString = String.format("https://api.pdfrest.com/request-status/%s", requestId);
Request request = new Request.Builder().header("Api-Key", apiKey).url(urlString).get().build();
try {
OkHttpClient client =
new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
Response response = client.newCall(request).execute();
System.out.println("Result code " + response.code());
if (response.body() != null) {
System.out.println(prettyJson(response.body().string()));
}
String responseBody = response.body().string();
System.out.println(prettyJson(responseBody));
return responseBody;
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand Down
2 changes: 1 addition & 1 deletion Java/Endpoint Examples/Multipart Payload/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
<version>4.12.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
Expand Down
51 changes: 38 additions & 13 deletions JavaScript/Endpoint Examples/Multipart Payload/request-status.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,43 @@
const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");

let config = {
method: "get",
maxBodyLength: Infinity, // set maximum length of the request body
url: "https://api.pdfrest.com/request-status/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
headers: { "Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }

const apiKey = "xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Replace with your API key
const pathToFile = "/path/to/file.pdf";

let bmpRequestData = new FormData();
bmpRequestData.append("file", fs.createReadStream(pathToFile));

let bmpConfig = {
method: "post",
maxBodyLength: Infinity,
url: "https://api.pdfrest.com/bmp",
headers: {
"Api-Key": apiKey,
"Response-Type": "requestId", // Use this header to get a request ID.
...bmpRequestData.getHeaders(),
},
data: bmpRequestData,
};

// define configuration options for axios request
axios
.request(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
axios(bmpConfig)
.then(bmpResponse => {
console.log(JSON.stringify(bmpResponse.data));
const requestId = bmpResponse.data.requestId;
let config = {
method: "get",
maxBodyLength: Infinity, // set maximum length of the request body
url: `https://api.pdfrest.com/request-status/${requestId}`,
headers: { "Api-Key": apiKey }
};
axios.request(config)
.then((requestStatusResponse) => {
console.log(JSON.stringify(requestStatusResponse.data));
})
.catch((error) => {
console.log(error);
});
}).catch(error => {
console.log(error);
});
})
38 changes: 33 additions & 5 deletions PHP/Endpoint Examples/Multipart Payload/request-status.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,47 @@
use GuzzleHttp\Psr7\Request; // Import the PSR-7 Request class.
use GuzzleHttp\Psr7\Utils; // Import the PSR-7 Utils class for working with streams.

$client = new Client(); // Create a new instance of the Guzzle HTTP client.
$client = new Client(); // Create a new instance of the Guzzle HTTP client

$requestId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; // place the requestId returned from a previous POST request here
$apiKey = 'xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'; // Your API key goes here.

$headers = [
'Api-Key' => $apiKey,
'response-type' => 'requestId'
];

$pngOptions = [
'multipart' => [
[
'name' => 'file',
'contents' => Utils::tryFopen('/path/to/file.pdf', 'r'),
'filename' => 'file.pdf',
'headers' => [
'Content-Type' => '<Content-type header>'
]
]
]
];

$pngRequest = new Request('POST', 'https://api.pdfrest.com/png', $headers);

$pngResponse = $client->sendAsync($pngRequest, $pngOptions)->wait();

echo $pngResponse->getBody();
echo "\r\n";

$requestId = json_decode($pngResponse->getBody())->{'requestId'};

$request_status_endpoint_url = 'https://api.pdfrest.com/request-status/'.$requestId;

$headers = [
'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Set the API key in the headers for authentication.
'Api-Key' => $apiKey
];

$request = new Request('GET', $request_status_endpoint_url, $headers); // Create a new HTTP GET request with the API endpoint and headers.
$request = new Request('GET', $request_status_endpoint_url, $headers);

$res = $client->sendAsync($request)->wait(); // Send the asynchronous request and wait for the response.
$res = $client->sendAsync($request)->wait();

echo $res->getBody(); // Output the response body, which contains the status information.
echo "\r\n";
?>
Loading
Loading