Search code examples
pythongoogle-drive-apigoogle-docsgoogle-docs-apigoogle-api-python-client

How to add local image to google docs using Google docs API and Python?


I want to add images in my google doc from my local system using google docs API but I read that it only accepts images from http servers

I tried uploading the image on google drive then used the drive image url in my code but it was throwing an error.

I don't want to allow the Internet to access the image from my local system as it won't be secure.

Is there any other way to add images to google docs from my local?

sample code (taken from Tanaike's solution):

{
            "insertInlineImage": {
                "location": {
                    "segmentId": header_id,
                    "index": 0
                },
                "uri": "https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.png",
                # This is a sample image.
                "objectSize": {
                    "width": {
                        "magnitude": 100,
                        "unit": "PT"
                    }
                }
            }
        }

Solution

  • You can follow this steps:

    1. Upload the image to drive.
    2. Double click on it. And go to Get-Link
    3. Set Anyone with the link as Viewer. and copy the file ID. For example: https://drive.google.com/file/d/FILE_ID/view?usp=sharing
    4. Go to your python script and add this as an uri
    "uri":"https://drive.google.com/uc?export=view&id=FILE_ID",
    
    1. Run the function that adds the image.

    This can also be achievable by uploading the file by Drive API and changing the permissions on the upload request.

    Refer the following for more documentation: