Sample code for 30+ languages & platforms
Swift

USPS OAuth2 Client Credentials

See more OAuth2 Examples

Get an OAuth2 access token for the United States Postal Service (USPS) REST API.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    let http = CkoHttp()!

    // Implements the following CURL command:

    // curl -X POST https://apis.usps.com/oauth2/v3/token \
    //   -H "Content-Type: application/x-www-form-urlencoded" \
    //   -d "grant_type=client_credentials" \
    //   -d "client_id=123456789" \
    //   -d "client_secret=A1B2C3D4E5" \
    //   -d "scope=ResourceA+ResourceB+ResourceC"

    // Use the following online tool to generate HTTP code from a CURL command
    // Convert a cURL Command to HTTP Source Code

    let req = CkoHttpRequest()!
    req.addParam(name: "grant_type", value: "client_credentials")
    req.addParam(name: "client_id", value: "123456789")
    req.addParam(name: "client_secret", value: "A1B2C3D4E5")
    req.addParam(name: "scope", value: "ResourceA+ResourceB+ResourceC")

    req.httpVerb = "POST"
    req.contentType = "application/x-www-form-urlencoded"

    let resp = CkoHttpResponse()!
    success = http.httpReq(url: "https://apis.usps.com/oauth2/v3/token", request: req, response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    let sbResponseBody = CkoStringBuilder()!
    resp.getBodySb(sb: sbResponseBody)

    let jResp = CkoJsonObject()!
    jResp.loadSb(sb: sbResponseBody)
    jResp.emitCompact = false

    print("Response Body:")
    print("\(jResp.emit()!)")

    var respStatusCode: Int = resp.statusCode.intValue
    print("Response Status Code = \(respStatusCode)")
    if respStatusCode >= 400 {
        print("Response Header:")
        print("\(resp.header!)")
        print("Failed.")
        return
    }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "access_token": "eyJraWQiOiIxMDEwMTAiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIiLCJhdWQiOiJhZGRyZXNzZXMgaW50ZXJuYXRpb25hbC1wcmljZXMgc3Vic2NyaXB0aW9ucyBwYXltZW50cyBwaWNrdXAgdHJhY2tpbmcgbGFiZWxzIHNjYW4tZm9ybXMgY29tcGFuaWVzIHNlcnZpY2UtZGVsaXZlcnktc3RhbmRhcmRzIGxvY2F0aW9ucyBpbnRlcm5hdGlvbmFsLWxhYmVscyBwcmljZXMiLCJhenAiOiJoeXI3YjN2Q1J0cFl0QUhNMWE4Y2RVcmt5eUZtTmtiZyIsIm9yZ2FuaXphdGlvbl9pZCI6IjAiLCJpc3MiOiJ1cm46XC9cL2FwaS51c3BzLmNvbSIsImV4cCI6MTY4MDkxNzc4NiwiaWF0IjoxNjgwODg4OTg2LCJqdGkiOiI3YjU5MzJlMS05NjIxLTQzZDAtYTMyNy0xMzIxYWVjNzJjZGYifQ.QzrUxlT2rG4jvYbMDGnk23j8ZYfHJcdXPKR9CbSmcKeVpURaHhEMpPB6K4x5ut3xxeEGSzeE5VRz8vixI4iqyHsD8rSdkLTPHy0iovUHOZQBAJVQ6hii9jpLhxUXmiTtH3jKzSj_f2fuNmZbIGhf-CR2FBeWF-aBPzEDEMV95nkCUMfW_Z2BmkbraSfvQZxkCO-cLrMAwlYcrzUtaJ7vnazeQB4sep5BBHBEvsa4kfq6_tz6BAKgv3R7cI2NkSv-wgy_IGoTjVCMTS8mJHGs_t8cWCO8-z4lxW1tUwIBKOCUDpmEEnGgiG6Sl0C_gGl4bZ5cDSl4IgPpcOVi9jZ7LA",
    //   "token_type": "Bearer",
    //   "issued_at": 1680888985929,
    //   "expires_in": 28799,
    //   "status": "approved",
    //   "scope": "addresses international-prices subscriptions payments pickup tracking labels scan-forms companies service-delivery-standards locations international-labels prices",
    //   "issuer": "api.usps.com",
    //   "client_id": "hyr7b3vCRtpYtAHM1a8cdUrkyyFmNkbg",
    //   "application_name": "Silver Shipper Developer",
    //   "api_products": "[Shipping-Silver]",
    //   "public_key": "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF4QWxwZjNSNEE1S0lwZnhJVWk1bgpMTFByZjZVZTV3MktzeGxSVzE1UWV0UzBjWGVxaW9OT2hXbDNaaVhEWEdKT3ZuK3RoY0NWVVQ3WC9JZWYvTENZCkhUWk1kYUJOdW55VHEwT2RNZmVkUU8zYUNKZmwvUnJPTHYyaG9TRDR4U1YxRzFuTTc1RTlRYitFZ1p0cmFEUXoKNW42SXRpMUMzOHFGMjU5NVRHUWVUemx3Wk1LQng1VTY2bGwzNzlkZ2plTUJxS3ppVHZHWEpOdVg5ZzRrRlBIaApTLzNERm9FNkVFSW8zUHExeDlXTnRaSm93VkRwQUVZZTQ3SU1UdXJDN2NGcXp2d3M1b1BDRHQ4c083N2lUdDN0Cm1vK3NrM2ExWnZSaGs2WUQ3Zkt1UldQVzFEYUM4dC9pazlnWnhqQndYNlZsSUhDRzRZSHlYejZteWdGV09jMmEKOVFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0t"
    // }

    // Sample code for parsing the JSON response...
    // Use the following online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    var access_token: String? = jResp.string(of: "access_token")
    var token_type: String? = jResp.string(of: "token_type")
    var issued_at: Int = jResp.int(of: "issued_at").intValue
    var expires_in: Int = jResp.int(of: "expires_in").intValue
    var status: String? = jResp.string(of: "status")
    var scope: String? = jResp.string(of: "scope")
    var issuer: String? = jResp.string(of: "issuer")
    var client_id: String? = jResp.string(of: "client_id")
    var application_name: String? = jResp.string(of: "application_name")
    var api_products: String? = jResp.string(of: "api_products")
    var public_key: String? = jResp.string(of: "public_key")

}