This is another simple example that help to access aws api using python and boto3. The python is most popular scripting language.I will use python flask micro rest framework to access amazon api.
The amazon provides different api packages based on programming languages.I am using boto3 libs which is based on python3 and provide interface to communicate with aws api.
we will use python 3+, flask microframework and boto3 libs. We will manage environment variable using python-dotenv package.
How to Consume Amazon API Using Python
We will create API that return availability zones using boto3.I am assuming you have created sample python flask app, if not please create app using my previous article Consuming a RESTful API with Python and Flask.
We will install boto3 and python-dotenv using below pip command –
pip install boto3 pip install python-dotenv
The pip command is help to install package as like npm, composer etc.
Let’s create .env
file into root of the application added below configuration params-
APP_ENV=Dev aws_access_key_id=XXXXXXXXXXXXXXXXXXXXXXX aws_secret_access_key=XXXXXXXXXXXXXXXXXXXXX region_name=XXXXXXXXXXXXXXXXX
Above configuration parameters will found into the aws account.
We will create route entry into the main api.py
file.
api.add_resource(getAvailabilityZones, "/get_availability_zones")
Create HTTP Get service Call using AWS HTTP Client
We will create HTTP client to get data from aws api, Now we will create service request to get data from aws server.We will create controller.py
file and added below code.
import boto3 from botocore.config import Config import botocore from botocore.exceptions import ClientError, BotoCoreError import logging import os class AWSService: def getAvailabilityZones(): try: ec2 = boto3.client('ec2', aws_access_key_id=os.getenv('aws_access_key_id'),aws_secret_access_key=os.getenv('aws_secret_access_key'), verify=False, api_version ='2016-11-15') response = ec2.describe_availability_zones() return Helper.jsonSuccess(results=response) except (ValueError, ClientError, BotoCoreError) as e: logging.exception(e) return Helper.jsonError(message=str(e)) return Helper.jsonError(message=str(e))
The post How To Access AWS Api Using Boto3 and Python appeared first on Rest Api Example.