Search code examples
amazon-web-servicesaws-api-gatewayamazon-cloudfront

How to use APIs to configure Cloudfront


I have used dedicated CDNs such as Fastly and Cloudflare, where I can use their REST APIs to configure settings, such as the front end and the back end. For example, for Fastly, I can simply send GET/POST/PUT request to https://api.fastly.com/ attached with my credential to retrieve/change/set various parameters.

I am learning AWS Cloudfront, and it seems it is way more complex than Fastly. All I can find is the Cloudfront API Reference, but it does not tell me what endpoint I will send the request to, and what credentials I am supposed to attach to my request. I wonder if there is any tutorial or documents that can help me get started.


Solution

  • The REST APIs are the APIs for AWS, but you usually don't want to use them directly but through a library or the AWS CLI.

    If you want to manually change resources through the API, use the AWS CLI: https://docs.aws.amazon.com/cli/latest/reference/cloudfront/index.html . You need to install it (https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) and add the access/secret keys (https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html).

    If you set up everything right, you can do everything through the CLI as you can do on the Console. For example, a aws cloudfront list-distributions gives back the distributions for the account.

    If you want to build automations that create and change distributions, you should use one of the SDKs, such as the NodeJS AWS SDK: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudFront.html . You also need to add access/secret keys, and then you can write any code you want that queries/modifies CloudFront. Such as (from the docs):

    var params = {
      Marker: 'STRING_VALUE',
      MaxItems: 'STRING_VALUE'
    };
    cloudfront.listDistributions(params, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });
    

    That said, the AWS APIs are rather complex and you can expect to spend quite some time experimenting with each call to get the desired result. A best practice is to set up your distribution using the console, then query the settings. This way you'll have an understanding what each parameter sets.