Error 400: redirect_uri_mismatch during Google Docs API authentication

I’m working on a Python project that extracts text from images using OCR and then saves that text into Google Docs. I’ve set up my credentials.json file correctly, but I keep encountering an issue when trying to authenticate with the API.

The error message that appears is:

Access denied: The request made by this application is not valid.

[email protected]
Unable to log in as this application sent a request that didn’t match the expected parameters. Please try again or get in touch with the developer for assistance. More details on this error can be found here.
The specific error is: Error 400: redirect_uri_mismatch.

Here’s the main code I’m using:

import streamlit as st
from PIL import Image
import pytesseract
import cv2
import os
import numpy as np

from modules.camera_handler import capture_image
from modules.file_handler import process_upload
from modules.ocr_processor import extract_text_content
from modules.google_docs import generate_new_doc

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

st.title('Image to Text Document Creator')
camera_mode = st.checkbox("Capture from Camera")
if camera_mode:
    input_image = capture_image()
else:
    input_image = process_upload()

left_col, right_col = st.columns(2)
display_img = left_col.checkbox("Display Image")
display_content = right_col.checkbox("Show Extracted Content")

image_display = st.container()
if display_img:
  with image_display:
    if input_image is not None:
      st.image(input_image)
    else:
      st.write("No image loaded")

if display_content:
    processed_text = extract_text_content(input_image)
    if processed_text is not None:
        text_output = st.text_area("OCR Results:", processed_text, height=150)
        doc_options = st.selectbox("Document Options:", ("Create New", "Update Existing"))
        if doc_options == "Create New":
            auth_file = 'credentials.json'
            if not auth_file:
                st.write("Google account authorization required:")
            if auth_file:
                new_doc_name = st.text_input("Document Name:")
                if st.button("Generate Document"):
                    document_id = generate_new_doc(auth_file, new_doc_name)
        else:
            st.write("Update existing document feature coming soon.")
    else:
        st.write("Please select an image or OCR processing failed.")

And here’s the function I created for Google Docs integration:

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def generate_new_doc(AUTH_FILE, DOCUMENT_NAME):
    REQUIRED_SCOPES = ['https://www.googleapis.com/auth/documents']
    # Setup OAuth flow
    oauth_flow = InstalledAppFlow.from_client_secrets_file(AUTH_FILE, REQUIRED_SCOPES)
    # Authenticate user
    user_creds = oauth_flow.run_local_server(port=0)
    # Initialize Docs API service
    docs_service = build('docs', 'v1', credentials=user_creds)
    # Document configuration
    doc_config = {
        'title': DOCUMENT_NAME
    }
    # Generate new document
    new_document = docs_service.documents().create(body=doc_config).execute()
    print(f"Document created successfully with ID: {new_document.get('id')}")

What could be causing this redirect URI mismatch error? I’ve thoroughly checked my setup, but I am still stuck at the authentication stage.

Had this exact same error building a document automation tool last year - super frustrating. The redirect_uri_mismatch happens because Google’s OAuth is trying to redirect to a localhost URL that wasn’t registered properly. When you use run_local_server(port=0), it grabs a random port, but your OAuth client config might not allow all localhost redirects. Check your Google Cloud Console under OAuth 2.0 Client IDs - make sure you’ve got http://localhost (no specific port) in your authorized redirect URIs. Even better, add http://localhost:8080 and http://127.0.0.1:8080 as backups. Sometimes it’s also mixed-up credential files or projects - your credentials.json needs to match the same project where you set up OAuth. Clearing browser cache before testing the auth flow again helped me too.

You’re getting this redirect_uri_mismatch error because there’s a mismatch between what’s configured in your Google Cloud Console and what your app is actually using. Since you’re using run_local_server(port=0) with dynamic ports, your OAuth client needs to be set as “Desktop application” - not “Web application”. I hit this exact same problem when I started working with Google APIs. Head to your Google Cloud Console, go to APIs & Credentials, find your OAuth 2.0 client ID, and check it’s set to “Desktop application”. If it says “Web application”, that’s your issue. Desktop apps handle dynamic ports automatically, but web apps need exact redirect URIs. Also make sure you’ve enabled the Google Docs API in your project’s API library.

check your google cloud console oauth settings - you probably created a web application client instead of desktop. web clients need exact redirect uris, but desktop clients handle dynamic ports fine (like your run_local_server(port=0)). i had this exact problem a few months back. just delete your current oauth client, create a new desktop one, download the fresh credentials.json and you’re good to go.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.