diff --git a/.gitignore b/.gitignore index e66cd32..d5178b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1287,3 +1287,5 @@ FodyWeavers.xsd Node/node_modules/ Node/package-lock.json +PHP/**/vendor/** +PHP/**/composer.* diff --git a/DotNET/Endpoint Examples/Multipart Payload/request-status.cs b/DotNET/Endpoint Examples/Multipart Payload/request-status.cs index cd9dbd5..5608a1c 100644 --- a/DotNET/Endpoint Examples/Multipart Payload/request-status.cs +++ b/DotNET/Endpoint Examples/Multipart Payload/request-status.cs @@ -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 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 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(); } } diff --git a/Java/Endpoint Examples/Multipart Payload/RequestStatus.java b/Java/Endpoint Examples/Multipart Payload/RequestStatus.java index 916cf61..0dc6e4e 100644 --- a/Java/Endpoint Examples/Multipart Payload/RequestStatus.java +++ b/Java/Endpoint Examples/Multipart Payload/RequestStatus.java @@ -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); } diff --git a/Java/Endpoint Examples/Multipart Payload/pom.xml b/Java/Endpoint Examples/Multipart Payload/pom.xml index a0eaa62..8574ff7 100644 --- a/Java/Endpoint Examples/Multipart Payload/pom.xml +++ b/Java/Endpoint Examples/Multipart Payload/pom.xml @@ -16,7 +16,7 @@ com.squareup.okhttp3 okhttp - 4.10.0 + 4.12.0 org.json diff --git a/JavaScript/Endpoint Examples/Multipart Payload/request-status.js b/JavaScript/Endpoint Examples/Multipart Payload/request-status.js index d397067..e541f37 100644 --- a/JavaScript/Endpoint Examples/Multipart Payload/request-status.js +++ b/JavaScript/Endpoint Examples/Multipart Payload/request-status.js @@ -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); - }); + }) diff --git a/PHP/Endpoint Examples/Multipart Payload/request-status.php b/PHP/Endpoint Examples/Multipart Payload/request-status.php index f8849a6..10859c5 100644 --- a/PHP/Endpoint Examples/Multipart Payload/request-status.php +++ b/PHP/Endpoint Examples/Multipart Payload/request-status.php @@ -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' => '' + ] + ] + ] +]; + +$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"; ?> diff --git a/Python/Endpoint Examples/Multipart Payload/request-status.py b/Python/Endpoint Examples/Multipart Payload/request-status.py index 4aa28ee..588e62f 100644 --- a/Python/Endpoint Examples/Multipart Payload/request-status.py +++ b/Python/Endpoint Examples/Multipart Payload/request-status.py @@ -2,23 +2,46 @@ import requests import json -api_polling_endpoint_url = 'https://api.pdfrest.com/request-status' +api_key = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here -request_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place requestId to poll here +pdfa_endpoint_url = 'https://api.pdfrest.com/pdfa' -api_polling_endpoint_url = f'https://api.pdfrest.com/request-status/{request_id}' +mp_encoder_pdfa = MultipartEncoder( + fields={ + 'file': ('file_name.pdf', open('/path/to/file.pdf', 'rb'), 'application/pdf'), + 'output_type': 'PDF/A-1b', + } +) -headers = { - 'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here +pdfa_headers = { + 'Accept': 'application/json', + 'Content-Type': mp_encoder_pdfa.content_type, + 'Response-Type': "requestId", + 'Api-Key': api_key } -print("Sending GET request to request-status endpoint...") -response = requests.get(api_polling_endpoint_url, headers=headers) +print("Sending POST request to pdfa endpoint...") +response = requests.post(pdfa_endpoint_url, data=mp_encoder_pdfa, headers=pdfa_headers) print("Response status code: " + str(response.status_code)) if response.ok: - response_json = response.json() - print(json.dumps(response_json, indent = 2)) -else: - print(response.text) + + response_json = response.json() + request_id = response_json["requestId"] + api_polling_endpoint_url = f'https://api.pdfrest.com/request-status/{request_id}' + + headers = { + 'Api-Key': api_key + } + + print("Sending GET request to request-status endpoint...") + response = requests.get(api_polling_endpoint_url, headers=headers) + + print("Response status code: " + str(response.status_code)) + + if response.ok: + response_json = response.json() + print(json.dumps(response_json, indent = 2)) + else: + print(response.text) diff --git a/cURL/Endpoint Examples/Multipart Payload/request-status.sh b/cURL/Endpoint Examples/Multipart Payload/request-status.sh old mode 100644 new mode 100755 index b7463dd..d62bcb8 --- a/cURL/Endpoint Examples/Multipart Payload/request-status.sh +++ b/cURL/Endpoint Examples/Multipart Payload/request-status.sh @@ -1,2 +1,16 @@ -curl -X GET "https://api.pdfrest.com/request-status/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" \ - -H "Api-Key: xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +#!/bin/sh + +API_KEY="xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + +REQUEST_ID=$(curl -X POST "https://api.pdfrest.com/pdfa" \ + -H "Accept: application/json" \ + -H "Content-Type: multipart/form-data" \ + -H "Api-Key: $API_KEY" \ + -H "response-type: requestId" \ + -F "file=@/path/to/file.pdf" \ + -F "output_type=PDF/A-3b" \ + -F "output=example_out" \ + | jq -r '.requestId') + +curl -X GET "https://api.pdfrest.com/request-status/$REQUEST_ID" \ + -H "Api-Key: $API_KEY" \ No newline at end of file