RapidParser bar
RapidParser Header Image
Table of Contents

REST Code Examples

In order to make the integration process as easy and comfortable as possible, we provide various code examples showing how to access the RapidParser web service for different programming languages. Currently, we list examples for both REST and SOAP access for the following languages/frameworks: C#, Java, NodeJS, PHP, Python, and Ruby.

C#

The following C# example shows how to use the RapidParser parse Web Service via REST. No further external libraries are required.

using System;
 
namespace rest_post
{
	# JSON-datastructure for easier serialization of payload
	public class JsonData
	{
		public String filename { get; set; }
		public String data { get; set; }
	}
 
	class MainClass
	{
		# Exemplary filename
		private const string fileName = "cv.pdf";
 
		public static void Main (string[] args)
		{
			# Read file and convert into Base64-string
			Byte[] bytes = System.IO.File.ReadAllBytes (fileName);
			String file = Convert.ToBase64String (bytes);
 
			# Create a JSON payload, convert to byte-array
			JsonData data = new JsonData ();
			data.filename = fileName;
			data.data = file;
			string json = new System.Web.Script.Serialization.JavaScriptSerializer ().Serialize (data);
			byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes (json);
 
			# Initialize request, set headers. Replace %TOKEN% with one of your tokens
			System.Net.HttpWebRequest req = System.Net.WebRequest.Create ("https://www.rapidparser.com/api/rest/v1/parse") 
				as System.Net.HttpWebRequest;
			req.Method = "POST";  
			req.ContentType = "application/json";
			req.Accept = "application/xml";
			req.Headers.Add ("Authorization", "Bearer %TOKEN%");
			req.ContentLength = jsonBytes.Length;
 
			string result = null;
			# Perform request, print result
			try {
				using (System.IO.Stream post = req.GetRequestStream ()) {  
					post.Write (jsonBytes, 0, jsonBytes.Length);  
				}
 
				using (System.Net.HttpWebResponse resp = req.GetResponse ()
				as System.Net.HttpWebResponse) {  
					result = new System.IO.StreamReader (resp.GetResponseStream ()).ReadToEnd ();
				}
			} catch (System.Net.WebException e) {
				result = new System.IO.StreamReader (e.Response.GetResponseStream()).ReadToEnd ();
			}
			Console.Write (result);
		}
	}
}

Java

The following Java example shows how to use the RapidParser parse Web Service via REST. Maven was used for dependency management, the following pom.xml excerpt shows how to add the required external libraries.

...
    <dependency>
      <groupId>com.sun.jersey>
      <artifactId>jersey-client>
      <version>1.8>
    >
    <dependency>
      <groupId>commons-codec>
      <artifactId>commons-codec>
      <version>1.4>
    >
    <dependency>
      <groupId>org.json>
      <artifactId>json>
      <version>20160212>
    >
...
import java.io.File;
import java.io.FileInputStream;
 
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
 
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
 
public class App {
	//exemplary filename
	private static final String filename = "cv.pdf";
 
	public static void main(String[] args) {
		try {
			// read file into base64-string
			File file = new File(filename);
			FileInputStream fis = new FileInputStream(file);
			byte[] bytes = new byte[(int) file.length()];
			fis.read(bytes);
			String fileBase64Encoded = new String(Base64.encodeBase64(bytes));
			fis.close();
 
			// prepare json-payload
			JSONObject obj = new JSONObject();
			obj.put("data", fileBase64Encoded);
			obj.put("filename", filename);
 
			// prepare and execute REST-call
			Client client = Client.create();
			WebResource webResource = client.resource("https://www.rapidparser.com/api/rest/v1/parse");
			ClientResponse response = null;
			response = webResource.type("application/json").accept("application/xml").header("Authorization", "Bearer %TOKEN%")
					.post(ClientResponse.class, obj.toString());
 
			// deserialize and print response
			String jsonStr = response.getEntity(String.class);
			System.out.println(jsonStr);
 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Node.js

The following example shows how to use the RapidParser parse Web Service via REST. No further external libraries are required.

// Exemplary filename
var filename = 'cv.pdf';
 
// Read file
require('fs').readFile(filename, function(err, data){
	if (err) { throw err; }
	// Convert file to Base64-string
	var base64_content = new Buffer(data).toString('base64');
 
	// Create JSON payload
	var payload = JSON.stringify({
		"filename":filename,
		"data":base64_content
	});
 
	// Set headers. Replace %TOKEN% with one of your tokens
	var postheaders = {
		'Content-Type':'application/json',
		'Accept':'application/xml',
		'Authorization':'Bearer %TOKEN%'
	};
 
	// Set request options
	var postOptions =
	{
		host: "www.rapidparser.com",
		port: "443",
		path: "/api/rest/v1/parse",
		method: 'POST',
		headers: postheaders
	};
 
	// Send request and print result
	var request = require('https').request(postOptions, function (res) {
		if(res.statusCode !== 200){
			console.log(res.statusCode);
			console.log(res.headers);
		}
 
		var str = "";
		res.on("data", function(chunk) {
			str += chunk;
		});
		res.on("end", function() {
			console.log(str);
		});
	});
	request.write(payload);
	request.end();
});

PHP

The following PHP example shows how to use the RapidParser parse Web Service via REST. No further external libraries are required.

// Exemplary filename
$filename = 'cv.pdf';
$service_url = 'https://www.rapidparser.com/api/rest/v1/parse';
 
// Read file and convert to Base64-string
$base64 = base64_encode(file_get_contents($filename));
$data = array(
	'filename' => $filename,
	'data' => $base64
);
 
// Create request headers. Replace %TOKEN% with one of your tokens
$headers = array('Content-Type: application/json', 'Authorization: Bearer %TOKEN%', 'Accept: application/xml');
 
// Set request parameter
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 
// Perform request and print results
$curl_response = curl_exec($curl);
curl_close($curl);
var_dump($curl_response);

Python

The following Python example shows how to use the RapidParser parse Web Service via REST. No further external libraries are required.

import urllib2
import json
# Exemplary filename
filename = 'cv.pdf'
 
# Read file and convert to Base64-string
base64 = open(filename,'rb').read().encode('base64')
 
# Set request parameter. Replace %TOKEN% with one of your tokens
req = urllib2.Request('https://www.rapidparser.com/api/rest/v1/parse')
req.add_header('Content-Type','application/json')
req.add_header('Accept','application/xml')
req.add_header('Authorization', 'Bearer %TOKEN%')
 
# Perform request and print results
try:
	res = urllib2.urlopen(req, json.dumps({'data':base64,'filename':filename}))
	print repr(res.read())
except urllib2.HTTPError, err:
	print 'Error ' + str(err.code) + ': ' + err.read()

Ruby

The following Ruby example shows how to use the RapidParser parse Web Service via REST. No further external gems are required.

require 'rest-client'
require 'base64'
# Exemplary filename
filename = "cv.pdf"
# Read file and convert to Base64
content = File.read(filename)
base64_content = Base64.encode64(content)
# Perform request and print response. Replace %TOKEN% with one of your tokens
response = RestClient.post("https://www.rapidparser.com/api/rest/v1/parse", 
                           {'data'=>base64_content,'filename'=>filename}.to_json, 
                           {"Authorization" => "Bearer %TOKEN%", :content_type => :json, :accept => :xml})
puts response