SkillSprout
Chapter 1 · Lesson 1
Beginner
6 min read

AWS SDKs, CLI and APIs

Overview

Every AWS feature is an HTTPS API. The console, the AWS CLI and the SDKs (boto3 for Python, AWS SDK for JavaScript v3, Java, .NET, Go and more) are all clients that build a request, sign it with Signature Version 4 (SigV4) and send it to a regional endpoint.

Think of the API as a restaurant kitchen's order window. The console is a waiter who takes your order, while the SDK is a self-service tablet that lets your own program place orders in exactly the right format, with your signature attached on every ticket.

As a developer you will mostly use SDKs inside applications and the CLI for scripting and exploration. Knowing configuration, pagination, waiters and error handling in both is directly tested on DVA-C02.

Key Concepts

  • AWS APIs are regional HTTPS endpoints; requests are authenticated with SigV4 signatures that SDKs compute for you.
  • The CLI and SDKs read region, credentials and profile from environment variables, shared config files or the runtime environment.
  • Named profiles in ~/.aws/config and ~/.aws/credentials let you switch accounts or roles with --profile.
  • Many list calls are paginated; use paginators (SDK) or --max-items / --page-size (CLI) and --query (JMESPath) to filter.
  • Waiters poll until a resource reaches a state, for example an instance running or a table active.
  • The SDK can target VPC endpoints, LocalStack or DynamoDB Local through a custom endpoint URL.
  • Use --dry-run (EC2) or --debug flags to check permissions and inspect requests.
  • Prefer the SDK default configuration and set the Region explicitly for each client.

Detailed Notes

Using the AWS CLI

The CLI is a thin wrapper over the APIs. Output can be json, yaml, text or table. --query filters output client-side with JMESPath, while --filter-style parameters (for example --filters on EC2) filter server-side.

bash
aws configure --profile dev
aws s3 ls --profile dev
aws ec2 describe-instances \
  --filters "Name=instance-state-name,Values=running" \
  --query "Reservations[].Instances[].{Id:InstanceId,Type:InstanceType}" \
  --output table
aws iam list-users --max-items 10 --page-size 5
aws ec2 run-instances --dry-run --image-id ami-123 --instance-type t3.micro

Config precedence

OrderSource (highest first)
1Command-line options (--region, --profile)
2Environment variables (AWS_REGION, AWS_PROFILE, AWS_ACCESS_KEY_ID)
3Shared credentials and config files
4Container credentials (ECS) or instance profile (EC2)

Python with boto3

boto3 has clients (low-level, one method per API call) and resources (object-oriented, higher level, mostly in maintenance mode). Paginators and waiters exist on clients.

python
import boto3

s3 = boto3.client("s3", region_name="eu-west-1")

paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket="my-bucket", Prefix="logs/"):
    for obj in page.get("Contents", []):
        print(obj["Key"], obj["Size"])

ec2 = boto3.client("ec2")
ec2.get_waiter("instance_running").wait(InstanceIds=["i-0abc"])

Node.js with SDK v3

SDK v3 is modular: install only the client packages you need and send command objects.

javascript
import { S3Client, ListObjectsV2Command } from "@aws-sdk/client-s3";

const s3 = new S3Client({ region: "eu-west-1" });
let token;
do {
  const out = await s3.send(new ListObjectsV2Command({
    Bucket: "my-bucket", ContinuationToken: token,
  }));
  (out.Contents ?? []).forEach((o) => console.log(o.Key));
  token = out.NextContinuationToken;
} while (token);

Creating clients efficiently

Create SDK clients outside request handlers (for example outside the Lambda handler) so connections and credentials are reused. A new client per request wastes time on TLS handshakes and credential resolution.

Error handling

SDK errors expose a code and HTTP status. 4xx means your request is wrong (do not retry, except throttling). 5xx means a service problem (retry). Catch specific codes such as ResourceNotFoundException.

python
from botocore.exceptions import ClientError

try:
    boto3.client("dynamodb").describe_table(TableName="orders")
except ClientError as e:
    code = e.response["Error"]["Code"]
    if code == "ResourceNotFoundException":
        print("table missing")
    else:
        raise

Decoding authorization failures

aws sts decode-authorization-message --encoded-message <msg> decodes the long text in an UnauthorizedOperation error to show which policy denied the call. The caller needs sts:DecodeAuthorizationMessage.

Configuration files and endpoints

Shared configuration lives in two INI files. Settings in config use the [profile name] header, while credentials uses plain [name] headers.

ini
# ~/.aws/config
[default]
region = eu-west-1
output = json
cli_pager =

[profile prod-readonly]
role_arn = arn:aws:iam::111122223333:role/ReadOnly
source_profile = default
mfa_serial = arn:aws:iam::444455556666:mfa/dev-user
retry_mode = standard
max_attempts = 5
SettingPurpose
regionDefault Region for requests
role_arn + source_profileAutomatically call STS and cache the temporary credentials
sso_sessionIAM Identity Center sign-in for humans
endpoint_urlPoint at LocalStack, DynamoDB Local or a VPC endpoint
retry_mode, max_attemptsRetry behaviour (see the retries lesson)

Debugging SDK calls

Turn on verbose logging when a call behaves unexpectedly. The request ID in every response lets AWS Support (and CloudTrail) find the exact call.

python
import boto3, logging
boto3.set_stream_logger("botocore", logging.DEBUG)   # prints signed requests and responses
resp = boto3.client("sts").get_caller_identity()
print(resp["ResponseMetadata"]["RequestId"], resp["Arn"])
bash
aws s3 ls --debug 2> debug.log     # headers, signing steps and credential source
aws dynamodb list-tables --endpoint-url http://localhost:8000   # DynamoDB Local
aws configure list                 # shows where each setting came from

Serialising data for AWS calls

SDKs differ in how they represent data. The DynamoDB low-level client uses typed attributes ({"S": "abc"}), while the document client (lib-dynamodb in JavaScript, boto3.resource in Python) converts native types for you. Python floats are rejected by DynamoDB; use Decimal. Binary payloads (Lambda invoke, Kinesis data) are base64 encoded in JSON, and the CLI needs --cli-binary-format raw-in-base64-out to pass raw text payloads.

Real World Example

A data team has a nightly Python script that lists millions of S3 objects. The original code called list_objects_v2 once and silently processed only the first 1,000 keys, so reports were wrong for weeks. After switching to a paginator, the script processed everything. They also moved client creation out of a loop and set the Region explicitly, which removed intermittent NoRegionError failures on build agents.

Architecture Diagram

How a CLI or SDK call reaches AWS
Architecture
Request path
Developer appSDK / CLI
Config + credentialsprofile / env
Region
Service endpointHTTPS
ServiceS3 / DynamoDB

The client resolves config, signs the request with SigV4 and calls a regional endpoint.

  1. 1The SDK reads the Region and finds credentials.
  2. 2It builds the API request and signs it with SigV4.
  3. 3The request goes over HTTPS to the regional endpoint.
  4. 4IAM authorises the call and the service returns JSON or XML.

Best Practices

  • ✓Create SDK clients once and reuse them across invocations.
  • ✓Always use paginators for list operations.
  • ✓Set the Region explicitly and never hard-code credentials.
  • ✓Use named profiles or SSO for humans and roles for workloads.
  • ✓Handle errors by code, retrying only retryable ones.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • A list call that returns incomplete data points to pagination.
  • CLI --query filters client-side; --filters filters server-side.
  • --dry-run checks permissions without performing an action.
  • Decode UnauthorizedOperation messages with STS decode-authorization-message.

Finished this lesson?

0 of 46 lessons done · 0% of the course