How to use Boto3 to get the table definition of a database from AWS Glue Data Catalog?


Problem Statement − Use boto3 library in Python to retrieve the table definition of a database.

Example − Retrieve the table definition of a database ‘QA-test’ and table as ‘security’.

Approach/Algorithm to solve this problem

Step 1 − Import boto3 and botocore exceptions to handle exceptions.

Step 2database_name and table_name is the mandatory parameter. It fetches the definition of given table.

Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.

Step 4 − Create an AWS client for glue.

Step 5 − Now use get_table function and pass the database_name as DatabaseName and table_name as Name parameter.

Step 6 − It returns the definition of a given table. If the table has multiple versions, it always fetches the details from current / latest version of table.

Step 7 − Handle the generic exception if something went wrong while checking the job.

Example

Use the following code to retrieve the table definition of a database −

import boto3
from botocore.exceptions import ClientError

def retrieves_table_details(database_name, table_name)
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.get_table(DatabaseName = database_name, Name = table_name)
      return response
   except ClientError as e:
      raise Exception("boto3 client error in retrieves_table_details: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in retrieves_table_details: " + e.__str__())
print(retrieves_table_details('QA-test', 'security'))

Output

{'Table': {'Name': 'security', 'DatabaseName': 'QA-test', 'Owner':
'owner', 'CreateTime': datetime.datetime(2020, 9, 10, 22, 27, 24,
tzinfo=tzlocal()), 'UpdateTime': datetime.datetime(2021, 2, 28, 10, 37,
33, tzinfo=tzlocal()), 'LastAccessTime': datetime.datetime(2020, 9, 10,
22, 27, 24, tzinfo=tzlocal()), 'Retention': 0, 'StorageDescriptor':
{'Columns': [{'Name': 'assettypecode', 'Type': 'string'}, {'Name':
'industrysector', 'Type': 'string'}, {'Name': 'securitycode', 'Type':
'char'}, {'Name': 'contractsize', 'Type': 'string'}, {'Name':
'conversionperiodenddate', 'Type': 'string'}, {'Name':
'conversionperiodstartdate', 'Type': 'string'}, {'Name':
'expirationdate', 'Type': 'string'}, {'Name': 'issuercountrycode',
'Type': 'string'}, {'Name': 'issuercountrydesc', 'Type': 'string'},
{'Name': 'originalissuedate', 'Type': 'string'}, {'Name':
'securitynamelong', 'Type': 'string'}, {'Name': 'issueshortname',
'Type': 'string'}, {'Name': 'gicssector', 'Type': 'string'}, {'Name':
'maturitydate', 'Type': 'string'}, {'Name': 'optioncode', 'Type':
'string'}, {'Name': 'optiontypename', 'Type': 'string'}, {'Name':
'paramount', 'Type': 'string'}, {'Name': 'priceindex', 'Type':
'string'}, {'Name': 'countrycoderisk', 'Type': 'string'}, {'Name':
'countrydescrisk', 'Type': 'string'}, {'Name': 'countrycode', 'Type':
'string'}], 'Location': 's3://test/security/', 'InputFormat':
'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat',
'OutputFormat':
'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat',
'Compressed': False, 'NumberOfBuckets': -1, 'SerdeInfo':
{'SerializationLibrary':
'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe',
'Parameters': {'serialization.format': '1'}}, 'BucketColumns': [],
'SortColumns': [], 'Parameters': {'CrawlerSchemaDeserializerVersion':
'1.0', 'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER':
'security', 'averageRecordSize': '181', 'classification': 'parquet',
'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800',
'sizeKey': '20337230', 'typeOfData': 'file'}, 'StoredAsSubDirectories':
False}, 'PartitionKeys': [], 'TableType': 'EXTERNAL_TABLE',
'Parameters': {'CrawlerSchemaDeserializerVersion': '1.0',
'CrawlerSchemaSerializerVersion': '1.0', 'UPDATED_BY_CRAWLER':
'security', 'averageRecordSize': '181', 'classification': 'parquet',
'compressionType': 'none', 'objectCount': '5', 'recordCount': '154800',
'sizeKey': '20337230', 'typeOfData': 'file'}, 'CreatedBy':
'arn:aws:sts::************:assumed-role/glue-role/AWS-Crawler'},
'ResponseMetadata': {'RequestId': '4c108dd5-***************76ac',
'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 01 Mar 2021
06:04:58 GMT', 'content-type': 'application/x-amz-json-1.1', 'contentlength': '3882', 'connection': 'keep-alive', 'x-amzn-requestid':
'4c108dd5-*********************676ac'}, 'RetryAttempts': 0}}

Updated on: 23-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements