close

How to check if DynamoDB table exists?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to check if DynamoDB table exists in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to check if DynamoDB table exists?

  1. How to check if DynamoDB table exists?

    Alternate approach if you do not want to use boto3.client but only boto3.resource:
    import boto3 database = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")

  2. check if DynamoDB table exists

    Alternate approach if you do not want to use boto3.client but only boto3.resource:
    import boto3 database = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")

Method 1

import boto3

from botocore.exceptions import ClientError

TABLE_NAME = "myTableName"
dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

table = dynamodb.Table(TABLE_NAME)

try:
    response = client.describe_table(TableName=TABLE_NAME)

except ClientError as ce:
if ce.response['Error']['Code'] == 'ResourceNotFoundException':
    print "Table " + TABLE_NAME + " does not exist. Create the table first and try again."
else:
    print "Unknown exception occurred while querying for the " + TABLE_NAME + " table. Printing full error:"
    pprint.pprint(ce.response)

Method 2

Alternate approach if you do not want to use boto3.client but only boto3.resource:

import boto3

database = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")    

table_name  = 'MyTable'
table_names = [table.name for table in database.tables.all()]

if table_name in table_names:
    print('table', table_name, 'exists')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read