Implement OCR API Using FastAPI - 1

Learn how to create a REST API that performs OCR on multiple images concurrently using FastAPI.

Create a virtual environment for our API

It is a best practice to create a virtual environment whenever you create a new project. You can follow one of the two options below:

  • Using the Anaconda Prompt:

    • Start the Anaconda Prompt.

    • Run the following command:

      conda create -n env_name python=3.7 
      

      You can specify any env_name you like and the desired Python version.

    • Activate your virtual environment by running the following command:

      conda activate env_name
      
    • Your environment is now activated and you can install whichever packages you need in this virtual environment.

  • Using venv package:

    • Start the Command Prompt.

    • If you do not have venv installed, you need to first install it by running the command shown below:

      pip install venv
      
    • Then, run the following command to create the virtual environment:

      python3 -m venv path\env_name
      

      You can specify any env_name you like. You need to specify the path where you want to store the files for your environment. By default, it will take the current directory.

    • Activate your virtual environment by running the following command:

      path\env_name\Scripts\activate
      
    • Your environment is now activated and you can install whichever packages you need in this virtual environment.

Create the default GET route

The first step in creating our REST API is to define a default (home) route that performs a GET operation. Whenever anyone tries to go the URL:

http://localhost:8000/

we will just give a JSON response as shown below:

{
   "message" : "Visit the endpoint: /api/v1/extract_text to perform OCR."
}

This means that the actual OCR operation is going to perform at the URL:

http://localhost:8000/api/v1/extract_text

with a request body containing the multipart/form-data, i.e., the images.

Note that we are going to pass multiple images in a single call, and our API should give the response in the form shown below:

{
   "image_name": "extracted_text"
}

Let’s first create the default GET route.

Get hands-on with 1200+ tech skills courses.