USPS API Examples

repository·main·Indexed 41 days ago

https://github.com/usps/api-examples

Developer tools and examples for integrating USPS postal services, including address validation, standardization, logistics, and shipping. Features documentation on OAuth 2.0 authentication, Carrier Pickup scheduling, container label creation, domestic label generation via the Labels API, and postage rate lookups for domestic and international mail.

Tokens
12.4K
Snippets
38
Records
43
Agent score
3%

What's inside USPS API

  1. Concept: Intelligent Mail Container barcode (IMcb)

    main

    The Intelligent Mail Container barcode (IMcb) provides visibility at the mail aggregate level. It is used on mailer-generated pallet labels to uniquely identify containers such as pallets, All Purpose Containers, hampers, and pallet boxes. The IMcb serves two primary purposes:

    1. It identifies the mail owner.
    2. It provides a link between the electronic mailing record and the physical mail aggregate.
  2. Use the USPS API Postman Collection

    main
    A Postman Collection is available to help you quickly test USPS API endpoints using the provided curl commands. You can import the Example-Postman.postman_collection.json file directly into Postman to jump-start your development.
  3. Switch between USPS Production and Test environments

    main
    By default, all USPS API documentation refers to Production URLs. To use the APIs in the USPS Test Environment, you must replace the base URL https://apis.usps.com with https://apis-tem.usps.com in your requests.
  4. Set up payment authorization for Domestic Labels

    main

    To use the USPS Labels API, you must first establish an Enterprise Payment Account. The API uses a specific token to authorize these transactions. You can generate a paymentAuthorizationToken by calling the payments API with your account details and roles (e.g., PAYER and LABEL_OWNER).

    Required fields for authorization:

    • accountType: Either EPS or PERMIT.
    • accountNumber: The account number for the specified type.
    • permitZIPCode: Required only if accountType is PERMIT.
    curl -X 'POST' 'https://apis.usps.com/payments/v3/payment-authorization' \
    	--header 'Content-Type: application/json' \
    	--header 'Authorization: Bearer $TOKEN' \
    	--data '{
    		"roles": [
    			{
    				"roleName": "PAYER",
    				"CRID": "XXXXXXXX",
    				"MID": "XXXXXXXXX",
    				"manifestMID": "XXXXXXXXX",
    				"accountType": "EPS",
    				"accountNumber": "XXXXXXXXXX"
    			},
    			{
    				"roleName": "LABEL_OWNER",
    				"CRID": "XXXXXXXX",
    				"MID": "XXXXXXXXX",
    				"manifestMID": "XXXXXXXXX",
    				"accountType": "EPS",
    				"accountNumber": "XXXXXXXXXX"
    			}
    		]
    	}'
  5. Authenticate with USPS APIs using OAuth 2.0

    main

    All USPS APIs require an OAuth 2.0 access token passed in the Authorization header using the Bearer token scheme.

    To authenticate, you must first register your application in the USPS Developer Portal to obtain a CLIENT_ID and CLIENT_SECRET. Additionally, you will need a valid Customer Registration ID (CUSTOMER_REGISTRATION_ID) and Mailer ID (MAILER_ID) from your USPS Business Customer Gateway Business System Administrator (BSA).

    Required credentials for setup:

    • CLIENT_ID
    • CLIENT_SECRET
    • CUSTOMER_REGISTRATION_ID
    • MAILER_ID
  6. Request an OAuth Authorization Code token

    main

    Use the authorization_code grant type to obtain an access token and a refresh_token by providing an authorization code obtained from the user.

    Endpoint: POST https://apis.usps.com/oauth2/v3/token

    curl -X 'POST' 'https://apis.usps.com/oauth2/v3/token' \
         --header 'Content-Type: application/json' \
         --data '{
    		"client_id": "{{CLIENT_ID}}",
    		"client_secret": "{{CLIENT_SECRET}}",
    		"code": "{{CODE}}",
    		"redirect_uri": "https://mycompany.com/authorize",
    		"scope": "prices labels tracking",
    		"state": "nonce=abscdefg#",
    		"grant_type": "authorization_code"
    		}'
  7. Refresh an OAuth access token

    main

    When an access token expires, use the refresh_token grant type to obtain a new access token without requiring user re-authentication.

    Endpoint: POST https://apis.usps.com/oauth2/v3/token

    curl -X 'POST' 'https://apis.usps.com/oauth2/v3/token' \
         --header 'Content-Type: application/json' \
         --data '{
    		"client_id": "{{CLIENT_ID}}",
    		"client_secret": "{{CLIENT_SECRET}}",
    		"grant_type": "refresh_token",
    		"refresh_token": "XXXXXXXXXXXXXXXXX"
    		}'
  8. Revoke an OAuth token

    main

    Use this endpoint to invalidate an existing token.

    Endpoint: POST https://apis.usps.com/oauth2/v3/revoke

    curl -X 'POST' 'https://apis.usps.com/oauth2/v3/revoke' \
    	--header 'Content-Type: application/json' \
    	--header 'Authorization: Bearer $TOKEN' \
    	--data '{
    		"token": "ExDTmpomcDt6pTbFVvSgQ1km39YmX8Oy",
    		"token_type_hint": "refresh_token"
    		}'
  9. Request an OAuth Client Credentials token

    main

    The client_credentials grant type is the primary OAuth flow supported by USPS. Use this to obtain an access token by providing your client credentials.

    Endpoint: POST https://apis.usps.com/oauth2/v3/token

    curl -X 'POST' 'https://apis.usps.com/oauth2/v3/token' \
         --header 'Content-Type: application/json' \
         --data '{
    		"client_id": "{{CLIENT_ID}}",
    		"client_secret": "{{CLIENT_SECRET}}",
    		"grant_type": "client_credentials"
    		}'
  10. Lookup domestic total rates including extra services

    main

    Use the total-rates/search endpoint to get a comprehensive price that includes both the base rate and selected extra services. This endpoint returns multiple rateOptions, each containing a totalBasePrice, a totalPrice (base + extra services), and the specific rates and extraServices used to calculate that total.

    curl  -X 'POST' 'https://apis.usps.com/prices/v3/total-rates/search' \
    		--header 'Content-Type: application/json' \
    		--header 'Authorization: Bearer $TOKEN' \
    		--data '{
    			"originZIPCode": "36105",
    			"destinationZIPCode": "78207",
    			"weight": 7,
    			"length": 9,
    			"width": 0.25,
    			"height": 6,
    			"mailClass": "PARCEL_SELECT",
    			"priceType": "COMMERCIAL",
    			"mailingDate": "2023-07-28",
    			"accountType": "EPS",
    			"accountNumber": "XXXXXXXXXX",
    			"itemValue": 500,
    			"extraServices": [
    				415
    			]
    		}'
  11. Schedule a Carrier Pickup

    main

    Create a new carrier pickup for a specified pickupDate. If the address is eligible, any future date can be selected (same-day availability is subject to time-of-day restrictions).

    Required data includes pickupDate, pickupAddress (with contact info), packages (specifying packageType and packageCount), estimatedWeight, and pickupLocation details.

    curl -X 'POST' 'https://apis.usps.com/pickup/v3/carrier-pickup' \
    --header 'Accept: application/json' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer $TOKEN' \
    --data-raw '{
      "pickupDate": "2023-04-21",
      "pickupAddress": {
        "firstName": "John",
        "lastName": "Smith",
        "firm": "FIRM",
        "address": {
          "streetAddress": "4120 Bingham",
          "streetAddressAbbreviation": "Ave",
          "secondaryAddress": null,
          "city": "Saint Louis",
          "cityAbbreviation": "",
          "state": "MO",
          "postalCode": "63116",
          "province": "",
          "ZIPCode": "63116",
          "ZIPPlus4": "2520",
          "urbanization": ""
        },
        "contact": [
          {"email":"john.smith@firm.com"},
          {"phone": "3333333333"}
        ]
      },
      "packages": [
        {
          "packageType": "FIRST-CLASS_PACKAGE_SERVICE",
          "packageCount": 1
        }
      ],
      "estimatedWeight": 5,
      "pickupLocation": {
        "packageLocation": "OFFICE",
        "specialInstructions": "Have a nice day"
      }
    }'