Build an Image-to-Text Extractor Application using API
Published: 2021-09-24 20:30:23

Text extraction is a process in which we extract ASCII characters from the image or a scanned document. This kind of application has a wide range of scope, including text recognition which further helps in various Machine Learning algorithms.  

In this article, we will build a simple yet powerful Text Extraction application using Pen to [Print - Handwriting OCR API and React](https://rapidapi.com/serendi/api/pen-to-print-handwriting-ocr/?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel).  

## How to connect to the Facial Text Analysis API

[RapidAPI](https://rapidapi.com/hub?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) handles all the API development things very effectively. You don't need to worry about any complicated stuff related to APIs like rate-limiting factors, authentication, and authorization. You just need to register on RapidAPI Hub if you want to use any API. RapidAPI provides you a single API key using which you can access over 35,000 APIs conveniently.   

Go to [RapidAPI Hub](https://rapidapi.com/hub?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) and create a free account.   

![sign up page of RapidAPI Hub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2bmz2oyq6j5rl9xswa8.png)

The majority of the APIs offer a freemium plan. You don't even need to add credit card details to access them. Let's choose the best-suited [pricing plan](https://rapidapi.com/serendi/api/pen-to-print-handwriting-ocr/pricing/?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) for Pen to Print - Handwriting OCR.  

The Basic plan of [Pen to Print - Handwriting OCR](https://rapidapi.com/serendi/api/pen-to-print-handwriting-ocr/?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) is free but keep in mind that it only offers 100 API calls per month. You can always change the plan according to your needs. Just click on the "Subscribe" button of the Basic plan.   

Now we are good to create a Text Extraction App using this API.   

![pricing page of Pen to Print = Handwriting OCR API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0p0ljyeg5krh53nuiiu.png)   

## Play around with Pen to Print - Handwriting OCR API

Once you subscribe, you can test the API and check the response this [Pen to Print - Handwriting OCR](https://rapidapi.com/serendi/api/pen-to-print-handwriting-ocr/?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) API returns. You can test multiple endpoints with different parameters using the API playground. Let's try to dig in with our current API to integrate it with our application.   

![homepage of pen to print - handwriting OCR](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2exzy2j72f4uso2x4r1.png)  

1. Endpoints
Here, you can take a quick look at the endpoints an interface supports. You can also search for a distinct endpoint.  

2. Documentation
Here, you can access and change all the necessary details required to test an endpoint. For example, you can pass values in the different parameters in the documentation section.

3. Code
Every developer wants and loves this section. You can copy-paste the code directly from here. RapidAPI supports 20 programming languages with 40 different libraries.   

The [Pen to Print - Handwriting OCR](https://rapidapi.com/serendi/api/pen-to-print-handwriting-ocr/?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) has only one endpoint which lets us make a POST request after uploading the image file from local storage. 

Scroll down a little bit in the documentation section. You will find a Request Body section, here you can pass all the necessary parameters. Upload an image from your device to test this API.   

Great, we are all set to hit the "Test Endpoint" button.

![test pen to print ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9v5vc6cnsy5x6bk3xj6t.png)
- handwriting OCR ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ula5x28rmm9ucwpivinb.png)   

After clicking the "Test Endpoint" button, you will see the endpoint (API) result in the third section of the API Playground. 

![response of pen to print - Handwriting OCR](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7sg1xa5x422r1w18yb2.png)

In the response body (returned data from the server) you will get a `value` key that contains all the text present in the image.  

## Integrate Pen to Print - Handwriting OCR API into Your React Application

[React](https://reactjs.org/) is a front-end JavaScript library for building user interfaces. In this article, you will learn how to integrate an API into your React application and build a text extraction application. Just follow the steps below:  

**1. Create a React Application** 

Create React App is the simplest way to set up a React application by running one command. 

```bash
npx create-react-app image-to-text 
```


You will need to have Node.js (version >= 6) on your local machine. If you haven't, just download it for free.  

Create-react-app command will create a folder for you with all the necessary files and folders required for a React application. You will get a `node_modules`, `public` and `src` folder.

![file structure of React app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgw9djoxxplb9mz4gp2s.png)

**2. Create a Form**

We want a form in our application where users can upload the image in order to extract text. We just need a file input field and a submit button in the form.  

Go to your project folder (image-to-text that we just created in the first step) and you'll find that React created a bunch of other folders and files for us. We don't need to check them all right now.  

Go to the `image-to-text folder > src > App.js` file and create a form with a file input field and a submit button.

```jsx
function App() {
  return (
    <div>
      <h1>Image to Text Extractor</h1>
      <form>
        <input type="file" />
        <input type="submit" value="Extract Text" />
      </form>
    </div>
  );
}
export default App;
```

Run the application to check the output by running the following command from the root of the project and go to [https://localhost:3000](https://localhost:3000):

```
npm start
```

![text extractor application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cc4o17r47869kzs8sww.png)
 
 
**3. Copy-paste the code snippet from RapidAPI Hub**

We are all set to integrate Text Analysis API code into our application. You don't even need to write the code. RapidAPI provides the code snippet in 20 programming languages with 40 libraries' support.   

Go to the [Pen to Print - Handwriting OCR](https://rapidapi.com/serendi/api/pen-to-print-handwriting-ocr/?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) API homepage and copy the code snippet from the Copy Snippets section of the API playground.   

Select the JavaScript language and [axios](https://github.com/axios/axios) method from the dropdown menu and click on the "Copy Code" button.

![copy code snippet of Pen to Print - Handwriting OCR API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8l1qj3tntyngowpofhz.png)

Create a `handleFormSubmit()` function in the App.js file and paste the code inside that function. 

We need to install the [axios](https://www.npmjs.com/package/axios) library first in order to use it in our application. Run the following command from the root of the project.

```
npm install axios 
``` 

**4. Let the user upload the image and extract the text**

We are almost done! We just need to validate the form so that the user can enter the text to get the result.   

Let's complete the form first. Create two `useState` hooks in the App.js file, one for handling the state binary image file to make the API call, and the second is for displaying the image that user uploads.
 
```javascript
const [previewImage, setPreviewImage] = useState("");
const [imageFile, setImageFile] = useState({});

<form onSubmit={handleFormSubmit}>
  <input type="file" onChange={handleFileInputChange} />
  <input type="submit" value="Extract Text" />
</form>
```

Call a function `handleFileInputChage` whenever a user uploads the new image file. Inside that function, we need to set the states so that we can display the preview image and convert the image file to binary in order to make the API call. 

```javascript
function handleFileInputChange(event) {
  setImageFile(event.target.files[0]);
  setPreviewImage(URL.createObjectURL(event.target.files[0]));
}
```
 
As simple as that, we are setting the binary format inside `imageFile` and object URL inside `previewImage` using [URL.createObjectURL](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) method.   

Let's create another useState hook for storing the response that the server returns.

```javascript
const [text, setText] = useState("");
```

Modify the `handleFormSubmit` function a little bit to store the `text` response string.  

```javascript
axios
  .request(options)
  .then(function (response) {
    setText(response.data.value);
  })
  .catch(function (error) {
    console.error(error);
  });
```

Render the extracted text on the webpage when the API successfully returns the data. You can do this by adding some paragraph tags inside the return method in the App.js file.   

If you missed some parts, this is how the entire App.js file looks like.  

```jsx
import axios from "axios";
import { useState } from "react";
function App() {
  const [previewImage, setPreviewImage] = useState("");
  const [imageFile, setImageFile] = useState({});
  const [text, setText] = useState("");
  function handleFileInputChange(event) {
    setImageFile(event.target.files[0]);
    setPreviewImage(URL.createObjectURL(event.target.files[0]));
  }
  function handleFormSubmit(event) {
    event.preventDefault();
    const form = new FormData();
    form.append("Session", "string");
    form.append("srcImg", imageFile);
    const options = {
      method: "POST",
      url: "https://pen-to-print-handwriting-ocr.p.rapidapi.com/recognize/",
      headers: {
        "content-type": "multipart/form-data",
        "x-rapidapi-host": "pen-to-print-handwriting-ocr.p.rapidapi.com",
        "x-rapidapi-key": process.env.REACT_APP_API_KEY,
      },
      data: form,
    };
    axios
      .request(options)
      .then(function (response) {
        setText(response.data.value);
      })
     .catch(function (error) {
       console.error(error);
     });
   }
  return (
    <div className="App">
      <h1>Image to Text Extractor</h1>
      <img src={previewImage} />
        <form onSubmit={handleFormSubmit}>
          <input type="file" onChange={handleFileInputChange} />
          <input type="submit" value="Extract Text" />
       </form>
       <p className="text">{text}</p>
     </div>
  );
}
export default App;
```

One important thing to note here is that we have passed the API key as   

```javascript
"x-rapidapi-key": process.env.REACT_APP_API_KEY,
```

`x-rapidapi-key` is your API key that RapidAPI provides using which you can access over 35,000 excellent APIs. It's always recommended to pass the API key as an environment variable because it's a confidential thing. Anyone can use your API subscription if they have your API key.   

Create a `.env` inside the `image-to-text` folder and add your API key inside REACT_APP_API_KEY(you can call it whatever you want but it should start with the prefix REACT_APP_ ) variable. Now you can access it inside the App.js file as process.env.REACT_APP_API_KEY.    

**5. Output**

Yay! Run the `npm start` command, and you'll see the result at [http://localhost:3000/](http://localhost:3000/).

![image to text extractor application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spkh8y45j3l3j7zebneo.png)

You can check the working project [here](https://codesandbox.io/s/image-to-text-ipgvn).  

You can add styling using CSS to make it look more appealing.

![final result of text extractor application](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p0g2p5zjgik3407e0up0.png)
 
Go to [RapidAPI Hub](https://rapidapi.com/hub?utm_source=dev.to%2FRapidAPI&utm_medium=DevRel&utm_campaign=DevRel) and create a free account to get your API key. The fun part is that you can use over 35,000 excellent APIs with just one API key. So it's worth creating a free account on RapidAPI Hub.     

Feel free to drop your suggestions, feedback, and doubts down below. We love checking them out.  

With that said, we hope you enjoy this article. Peace out!! Keep coding! We will catch you with the next excellent project idea.