Sample code for 30+ languages & platforms
C Requires Chilkat v11.6.0+

Amazon SQS: Purge a Queue (Deletes All Messages)

See more Amazon SQS Examples

Destructive operation: PurgeQueue removes available and in-flight messages while retaining the queue and its configuration. Deleted messages cannot be recovered. The code defaults to purgeConfirmed=false and sends no request until you deliberately enable it.

Purge can take up to 60 seconds. Messages sent during that window may also be deleted. Stop or coordinate producers and consumers, verify the target account/region/queue, and wait at least 60 seconds before resuming traffic. PurgeQueueInProgress indicates a purge request within the preceding 60 seconds; it is not a successful second purge. HTTP 200 confirms acceptance, not completion. The JSON protocol returns an empty body; an empty JSON object is also accepted by this example.

Uses SQS's AWS JSON protocol: POST to the regional root / with Content-Type: application/x-amz-json-1.0 and an operation-specific X-Amz-Target: AmazonSQS.... Chilkat.Rest and AuthAws sign with AWS Signature Version 4, service sqs. AWS still supports the older Query/XML protocol; these examples use JSON for simpler request and response handling. No AWS SDK is required.

Provide current IAM credentials in a private qa_data/aws/sqs.json with string fields access_key, secret_key, and session_token for temporary credentials. Queue-specific examples also read queue_url from this file. Set the region in the code to match the queue. These examples use commercial regional endpoints; other partitions or custom endpoints require corresponding changes. Prefer short-lived role credentials. The file is explicitly loaded; profiles and credential refresh are not automatic. Keep it outside public content and source control. The temporary token is included in the signed query; keep URLs and diagnostics private. TLS certificate verification is enabled.

Transport completion, HTTP status, and response validity are checked separately. Use bounded backoff with jitter for retryable errors, and refresh expired credentials. A timed-out write or receive may already have been accepted. Standard queues can deliver duplicates: make application processing idempotent and delete only after successful processing. Automatic reconnection is disabled for writes and receives to avoid replay after a lost response. Read-only queue listing permits reconnection.

Required IAM action: sqs:PurgeQueue. Scope access to the intended queue. Customer-managed KMS encryption can require additional KMS permissions for producers and consumers.

AWS PurgeQueue reference

Chilkat C Downloads

C
#include <C_CkStringBuilder.h>
#include <C_CkJsonObject.h>
#include <C_CkAuthAws.h>
#include <C_CkRest.h>
#include <C_CkSocket.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkStringBuilder textCompare;
    BOOL purgeConfirmed;
    HCkJsonObject credentials;
    BOOL sameText1;
    BOOL sameText2;
    const char *region;
    HCkStringBuilder endpoint;
    const char *queueUrl;
    BOOL sameText3;
    HCkStringBuilder expectedPrefix;
    HCkStringBuilder queueText;
    HCkAuthAws aws;
    HCkRest rest;
    BOOL sameText4;
    HCkSocket connection;
    HCkJsonObject body;
    HCkJsonObject result;
    HCkStringBuilder requestBody;
    HCkStringBuilder responseBody;

    success = FALSE;

    //  StringBuilder compares text by value in every generated language.
    textCompare = CkStringBuilder_Create();
    //  DESTRUCTIVE: removes available AND in-flight messages from the entire queue.
    //  Confirm the account/region/queue, and stop producers/consumers as appropriate.
    purgeConfirmed = FALSE;
    if (purgeConfirmed != TRUE) {
        printf("Purge disabled. Review the target queue and set purgeConfirmed to true deliberately.\n");
        CkStringBuilder_Dispose(textCompare);
        return;
    }

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = FALSE;
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the SQS operation.
    credentials = CkJsonObject_Create();
    CkJsonObject_putStrict(credentials,TRUE);
    success = CkJsonObject_LoadFile(credentials,"qa_data/aws/sqs.json");
    if (success != TRUE) {
        printf("Could not load private AWS credentials.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        return;
    }

    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkJsonObject_stringOf(credentials,"access_key"));
    sameText1 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
    if ((CkJsonObject_JsonTypeOf(credentials,"access_key") != 1) || (sameText1 == TRUE)) {
        printf("Missing or invalid access_key.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        return;
    }

    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkJsonObject_stringOf(credentials,"secret_key"));
    sameText2 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
    if ((CkJsonObject_JsonTypeOf(credentials,"secret_key") != 1) || (sameText2 == TRUE)) {
        printf("Missing or invalid secret_key.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        return;
    }

    //  Set this once to the region containing the queue.
    region = "us-west-2";
    endpoint = CkStringBuilder_Create();
    success = CkStringBuilder_Append(endpoint,"sqs.");
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        return;
    }

    success = CkStringBuilder_Append(endpoint,region);
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        return;
    }

    success = CkStringBuilder_Append(endpoint,".amazonaws.com");
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        return;
    }

    //  Use the exact QueueUrl returned by CreateQueue, GetQueueUrl, or ListQueues.
    //  This example targets a standard commercial regional endpoint, not a custom endpoint.
    queueUrl = CkJsonObject_stringOf(credentials,"queue_url");
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,queueUrl);
    sameText3 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
    if ((CkJsonObject_JsonTypeOf(credentials,"queue_url") != 1) || (sameText3 == TRUE)) {
        printf("Missing or invalid queue_url in sqs.json.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        return;
    }

    expectedPrefix = CkStringBuilder_Create();
    success = CkStringBuilder_Append(expectedPrefix,"https://");
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        return;
    }

    success = CkStringBuilder_Append(expectedPrefix,CkStringBuilder_getAsString(endpoint));
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        return;
    }

    success = CkStringBuilder_Append(expectedPrefix,"/");
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        return;
    }

    queueText = CkStringBuilder_Create();
    success = CkStringBuilder_Append(queueText,queueUrl);
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        return;
    }

    if (CkStringBuilder_StartsWith(queueText,CkStringBuilder_getAsString(expectedPrefix),TRUE) != TRUE) {
        printf("Queue URL must use HTTPS and the configured SQS region.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        return;
    }

    aws = CkAuthAws_Create();
    CkAuthAws_putAccessKey(aws,CkJsonObject_stringOf(credentials,"access_key"));
    CkAuthAws_putSecretKey(aws,CkJsonObject_stringOf(credentials,"secret_key"));
    CkAuthAws_putRegion(aws,region);
    CkAuthAws_putServiceName(aws,"sqs");
    CkAuthAws_putSignatureVersion(aws,4);
    rest = CkRest_Create();
    CkRest_putConnectTimeoutMs(rest,20000);
    CkRest_putIdleTimeoutMs(rest,60000);
    success = CkRest_SetAuthAws(rest,aws);
    if (success != TRUE) {
        printf("Could not configure AWS signing.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        return;
    }

    //  Temporary IAM/STS credentials require their session token on every signed request.
    //  AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
    //  Leave session_token absent or empty only for credentials that do not have one.
    if (CkJsonObject_HasMember(credentials,"session_token") == TRUE) {
        if (CkJsonObject_JsonTypeOf(credentials,"session_token") != 1) {
            printf("session_token must be a string.\n");
            CkStringBuilder_Dispose(textCompare);
            CkJsonObject_Dispose(credentials);
            CkStringBuilder_Dispose(endpoint);
            CkStringBuilder_Dispose(expectedPrefix);
            CkStringBuilder_Dispose(queueText);
            CkAuthAws_Dispose(aws);
            CkRest_Dispose(rest);
            return;
        }

        CkStringBuilder_Clear(textCompare);
        CkStringBuilder_SetString(textCompare,CkJsonObject_stringOf(credentials,"session_token"));
        sameText4 = CkStringBuilder_ContentsEqual(textCompare,"",TRUE);
        if (sameText4 != TRUE) {
            success = CkRest_AddQueryParam(rest,"X-Amz-Security-Token",CkJsonObject_stringOf(credentials,"session_token"));
            if (success != TRUE) {
                printf("Could not set the session-token parameter.\n");
                CkStringBuilder_Dispose(textCompare);
                CkJsonObject_Dispose(credentials);
                CkStringBuilder_Dispose(endpoint);
                CkStringBuilder_Dispose(expectedPrefix);
                CkStringBuilder_Dispose(queueText);
                CkAuthAws_Dispose(aws);
                CkRest_Dispose(rest);
                return;
            }

        }

    }

    //  Supply a Socket to explicitly enable TLS certificate verification.
    connection = CkSocket_Create();
    CkSocket_putRequireSslCertVerify(connection,TRUE);
    CkSocket_putMaxReadIdleMs(connection,60000);
    CkSocket_putMaxSendIdleMs(connection,60000);
    success = CkSocket_Connect(connection,CkStringBuilder_getAsString(endpoint),443,TRUE,20000);
    if (success != TRUE) {
        printf("TLS connection failed; inspect diagnostics privately.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        return;
    }

    //  Do not automatically reconnect/replay a write or receive after a lost response.
    success = CkRest_UseConnection(rest,connection,FALSE);
    if (success != TRUE) {
        printf("Could not attach the TLS connection.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        return;
    }

    success = CkRest_AddHeader(rest,"Content-Type","application/x-amz-json-1.0");
    if (success != TRUE) {
        printf("Could not set the content type.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        return;
    }

    body = CkJsonObject_Create();
    result = CkJsonObject_Create();
    CkJsonObject_putStrict(result,TRUE);
    requestBody = CkStringBuilder_Create();
    responseBody = CkStringBuilder_Create();
    success = CkRest_AddHeader(rest,"X-Amz-Target","AmazonSQS.PurgeQueue");
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        CkJsonObject_Dispose(body);
        CkJsonObject_Dispose(result);
        CkStringBuilder_Dispose(requestBody);
        CkStringBuilder_Dispose(responseBody);
        return;
    }

    success = CkJsonObject_UpdateString(body,"QueueUrl",queueUrl);
    if (success != TRUE) {
        printf("Could not prepare the request.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        CkJsonObject_Dispose(body);
        CkJsonObject_Dispose(result);
        CkStringBuilder_Dispose(requestBody);
        CkStringBuilder_Dispose(responseBody);
        return;
    }

    //  EmitSb appends, so clear both builders before each request/page.
    CkStringBuilder_Clear(requestBody);
    CkStringBuilder_Clear(responseBody);
    success = CkJsonObject_EmitSb(body,requestBody);
    if (success != TRUE) {
        printf("Could not serialize JSON.\n");
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        CkJsonObject_Dispose(body);
        CkJsonObject_Dispose(result);
        CkStringBuilder_Dispose(requestBody);
        CkStringBuilder_Dispose(responseBody);
        return;
    }

    success = CkRest_FullRequestSb(rest,"POST","/",requestBody,responseBody);
    if (success != TRUE) {
        printf("Request did not complete; inspect diagnostics privately.\n");
        //  A write or receive may have reached SQS. Do not blindly replay it.
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        CkJsonObject_Dispose(body);
        CkJsonObject_Dispose(result);
        CkStringBuilder_Dispose(requestBody);
        CkStringBuilder_Dispose(responseBody);
        return;
    }

    if (CkRest_getResponseStatusCode(rest) != 200) {
        printf("SQS HTTP status: %d\n",CkRest_getResponseStatusCode(rest));
        printf("AWS request ID: %s\n",CkRest_responseHdrByName(rest,"x-amzn-RequestId"));
        success = CkJsonObject_LoadSb(result,responseBody);
        if ((success == TRUE) && (CkJsonObject_JsonTypeOf(result,"__type") == 1)) {
            printf("AWS error type: %s\n",CkJsonObject_stringOf(result,"__type"));
        }
        else {
            printf("AWS error type: %s\n",CkRest_responseHdrByName(rest,"x-amzn-errortype"));
        }

        //  Error messages, payloads, receipt handles and signed URLs can be private.
        //  HTTP 400 can be throttling, expired credentials, or invalid parameters.
        CkStringBuilder_Dispose(textCompare);
        CkJsonObject_Dispose(credentials);
        CkStringBuilder_Dispose(endpoint);
        CkStringBuilder_Dispose(expectedPrefix);
        CkStringBuilder_Dispose(queueText);
        CkAuthAws_Dispose(aws);
        CkRest_Dispose(rest);
        CkSocket_Dispose(connection);
        CkJsonObject_Dispose(body);
        CkJsonObject_Dispose(result);
        CkStringBuilder_Dispose(requestBody);
        CkStringBuilder_Dispose(responseBody);
        return;
    }

    //  DeleteMessage and PurgeQueue normally return an empty HTTP body.
    //  Also accept an empty JSON object; never require XML for this protocol.
    if (CkStringBuilder_getLength(responseBody) > 0) {
        success = CkStringBuilder_Trim(responseBody);
        if (success != TRUE) {
            printf("Could not inspect response.\n");
            CkStringBuilder_Dispose(textCompare);
            CkJsonObject_Dispose(credentials);
            CkStringBuilder_Dispose(endpoint);
            CkStringBuilder_Dispose(expectedPrefix);
            CkStringBuilder_Dispose(queueText);
            CkAuthAws_Dispose(aws);
            CkRest_Dispose(rest);
            CkSocket_Dispose(connection);
            CkJsonObject_Dispose(body);
            CkJsonObject_Dispose(result);
            CkStringBuilder_Dispose(requestBody);
            CkStringBuilder_Dispose(responseBody);
            return;
        }

        if (CkStringBuilder_StartsWith(responseBody,"{",TRUE) != TRUE) {
            printf("Expected a JSON object response.\n");
            CkStringBuilder_Dispose(textCompare);
            CkJsonObject_Dispose(credentials);
            CkStringBuilder_Dispose(endpoint);
            CkStringBuilder_Dispose(expectedPrefix);
            CkStringBuilder_Dispose(queueText);
            CkAuthAws_Dispose(aws);
            CkRest_Dispose(rest);
            CkSocket_Dispose(connection);
            CkJsonObject_Dispose(body);
            CkJsonObject_Dispose(result);
            CkStringBuilder_Dispose(requestBody);
            CkStringBuilder_Dispose(responseBody);
            return;
        }

        success = CkJsonObject_LoadSb(result,responseBody);
        if (success != TRUE) {
            printf("Expected well-formed JSON.\n");
            CkStringBuilder_Dispose(textCompare);
            CkJsonObject_Dispose(credentials);
            CkStringBuilder_Dispose(endpoint);
            CkStringBuilder_Dispose(expectedPrefix);
            CkStringBuilder_Dispose(queueText);
            CkAuthAws_Dispose(aws);
            CkRest_Dispose(rest);
            CkSocket_Dispose(connection);
            CkJsonObject_Dispose(body);
            CkJsonObject_Dispose(result);
            CkStringBuilder_Dispose(requestBody);
            CkStringBuilder_Dispose(responseBody);
            return;
        }

        if (CkJsonObject_getSize(result) != 0) {
            printf("Unexpected fields in the empty-result response.\n");
            CkStringBuilder_Dispose(textCompare);
            CkJsonObject_Dispose(credentials);
            CkStringBuilder_Dispose(endpoint);
            CkStringBuilder_Dispose(expectedPrefix);
            CkStringBuilder_Dispose(queueText);
            CkAuthAws_Dispose(aws);
            CkRest_Dispose(rest);
            CkSocket_Dispose(connection);
            CkJsonObject_Dispose(body);
            CkJsonObject_Dispose(result);
            CkStringBuilder_Dispose(requestBody);
            CkStringBuilder_Dispose(responseBody);
            return;
        }

    }

    printf("Purge request accepted. Wait at least 60 seconds before resuming queue traffic.\n");
    //  Acceptance is not completion. Messages sent during the purge may also be deleted.
    //  Do not send another purge within 60 seconds; PurgeQueueInProgress is an error.


    CkStringBuilder_Dispose(textCompare);
    CkJsonObject_Dispose(credentials);
    CkStringBuilder_Dispose(endpoint);
    CkStringBuilder_Dispose(expectedPrefix);
    CkStringBuilder_Dispose(queueText);
    CkAuthAws_Dispose(aws);
    CkRest_Dispose(rest);
    CkSocket_Dispose(connection);
    CkJsonObject_Dispose(body);
    CkJsonObject_Dispose(result);
    CkStringBuilder_Dispose(requestBody);
    CkStringBuilder_Dispose(responseBody);

    }