Postman pre-request script, never worry about refreshing your access token

One of the most common tasks when you work with APIs is trying to ping them to see if they work as intended (also known as: testing).

One of the simplest, more useful tool on the market is Postman, an API client that lets you make requests to any URL you like, using all the methods you could dream of. You can even specify some HTTP headers, which are useful if you must pass an access token in the request to authenticate your API call.

And that’s where I began encountering a problem. Not a problem, per se, but something even worse for a Cloud Engineer: repetition.

You see, in order to pass this access token to the request, you must first generate it (usually from another API call). The thing is, this access token is short-lived, and will expire after 1 hour of its generation.

So, what does that imply? Well, every hour, before making another request to your API, you will have to make a first request to get a brand new access token, copy the result, and paste it in the appropriate header of your initial request. In total, this will make you lost 10 seconds.

Ugh! Can you imagine? 10 seconds?! All the things that could be done if we managed to get this precious time back!

Is It Worth the Time? - by xkcd
Is It Worth the Time? – from xkcd

But in a product like Postman, I knew this could be resolved somehow. And indeed, after literally one single web search, I stumbled across the perfect solution: Pre-request script.

The idea is pretty simple: execute a script before any request. That’s it.

How is this going to help us, you ask? Well, we can now write a small piece of code, that will get a new access token and store it it the variables of the collection we’re in. Then, our requests will always reference this variable to be sure they have an up-to-date token.

Let me show you an example I used in one of my projects where I needed to get an AWS Cognito access token before each request.

pm.sendRequest({
    url: "https://YOUR_COGNITO_DOMAIN_NAME_HERE.auth.eu-west-1.amazoncognito.com/oauth2/token",
    method: 'POST',
    header: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            {
                key: "grant_type",
                value: "client_credentials"
            },
            {
                key: "client_id",
                value: "YOUR_CLIENT_ID_HERE"
            },
            {
                key: "client_secret",
                value: "YOUR_CLIENT_SECRET_HERE"
            },
            {
                key: "scope",
                value: "YOUR_SCOPE_HERE"
            }
        ]
    }
}, (err, res) => {
    pm.collectionVariables.set("access_token", res.json().access_token)
});

As you can see, this is pretty straightforward, and can probably be applied to any of your projects that require OAuth authentication.

I hope this has been helpful and don’t forget: if you can save 10 seconds, do it!

The Rubber Duck Debugging – why does it work?

Programmation is a painful art. You are a real architect and you mission is to design, build, decorate and maintain an application, much like how you would do for a house.

One difficulty emerges though: you have to communicate information with a machine through programming languages to make everything work. Surely you don’t talk to your furnitures to place them into your house, right? Right?

This little difference is crucial, as you sometimes will encounter an issue that you have no idea why it is there. Truly you developed this thing so perfectly that it should not fail. But here we are, a bug is there and you don’t know why.

The first thing to do is of course to blame it on the computer. I mean, you know what you’re doing, there is no way you wrote something the wrong way. It’s probably this damn laptop which is making you look like a fool again. But the truth is hard to swallow.

The machine does exactly what you tell it to do.

Bill Gates, probably

Like it or not, your computer is dumb. It will mindlessly retrieve the information you provided and execute them. And if it fails, it is, without a doubt, your fault. I know the pain, trust me. But don’t worry too much, it happened to every one of us, and at the end of the day, everything will be fine.

Now, it is all up to you. You know that you did something wrong, yet are unable to find what.So what’s next? Should look up answers on StackOverflow? Resign of your position as you clearly are not good enough for this job? The answer is simple.

The first step when you are stuck, is to ask the wisdom of the duck.

I know what you’re thinking right now: What are you smoking and where can I get some? But trust me, this whole duck thing is not an hallucination, it is THE best way to help you.

Don’t worry though, you won’t need to drive to the nearest farm and steal a duck to apply this advice. In our case, a rubber duck is what we need.

Once you get your hands on one and place it on your desk, the only thing left is to talk to him. Go ahead, don’t be shy and explain to him what’s happening with your code.

I’d rather tell about it right now so you don’t end up shocked when confronted with the truth, but the duck will not respond to you. Hearth-breaking, I know. However, he is the perfect listener and his patience is way above any other human being unlike your co-workers. Moreover, the duck will never judge your mistakes. He is kind and comprehensive.

And the more you will explain to him your troubles, the more you’ll realise what was wrong all along in your code. Indeed, trying to explain properly to the duck what you are trying to do will expose a tiny inconsistency between what you did and what you are trying to achieve. Slowly but surely, you will soon enough be able to pinpoint the exact line of code that was causing all your troubles and fix it like the pro you are.

And that’s why the duck is so useful. Not only did you let your coworkers work in peace, this exercice forces you to take a step back at your code so that you can explain it to someone who has no clue of what’s going on.

This effort to put words on the expected behaviour and what you were able to achieve for now will highlight any potential mistakes you might have made during the development, things that can’t be seen when you spent eight hours looking at your code non-stop.

In describing what the code is supposed to do and observing what it actually does, any incongruity between these two becomes apparent.

Stephen J. Baker

So next time you’re stuck on something, don’t bother your co-workers, save your internet data and simply ask the duck!

If you wish to learn more on this method, I strongly suggest having a look at the website behind this post’s inspiration.

https://rubberduckdebugging.com/

FizzBuzz, the simplest, more efficient way to test a developer

When I got out of my engineering school, I passed a lot of interviews in the hope of getting a developer job. My experiences being limited to having done a few internships, I was fearing the part of the interview where I would have had to get up and resolve some complex algorithm exercice on a white board, or even just answer a few technical questions. I was wrong.

Not a single interview tested me on my development skills.

I could’ve lied my way through the whole interview that I would still have gotten the job.

To be honest, I’m not part of the people who praise technical questions like it is some kind of magic spell to detect good programmers. I’d rather think than someone with a good temperament, passionate and humanely pleasant is much more appreciated than a know-it-all who always brings his science to the table without wanting to hear anyone else opinions. You can improve a technical gap, but you can’t improve a shitty character.

I do believe however that it is mandatory to at least check the way of thinking of someone when being confronted to a problem. Because in the end, that’s what he is gonna do most of his job: resolve problems. As such, it is crucial to see how someone will behave when being presented a problem. Will he run away? Will he immediately ask for help?

That’s when the FizzBuzz test comes into play.

This post was inspired by Tom Scott’s video that I strongly suggest you to have a look at if this topic interests you.

The idea behind FizzBuzz is straight-forward. You need to count out loud numbers starting at 1 until you reach 100. But, if the number is a multiple of 3, you have to say the word “Fizz” instead. In the same way, if the number is a multiple of 5, you have to say the word “Buzz”. Now you might be thinking: “Then what am I supposed to do when it is a multiple of both 3 and 5?”. Well, you would simply have to say “FizzBuzz”. Roll credits.

By reading this simple test, you might wonder why this should be used, as it appears that even an intern could solve it quite easily. Well, that’s what I thought too, until I ran accros Jeff Atwood’s post on this subject, stating that he was surprised how this problem actually gave a lot of troubles to candidates, even senior ones.

So let’s try to solve it together!

In most technical interviews and as such for this exercice, you are free to use any programming language you feel most confortable with, or even write using pseudocode. For this post, I’m gonna use Python.

First things first, let’s create a simple loop that prints all numbers from 1 to 100.

for i in range(1, 101):
    print(i)

Off to a great start! Now let’s review the original statement: if the number is a multiple of 3, show “Fizz”, if the number is a multiple of 5, show “Buzz”. No Let’s add these conditions.

for i in range(1, 101):
    if i % 3 == 0:
        print('Fizz')
    if i % 5 == 0:
        print('Buzz')
    if i % 3 != 0 and i % 5 != 0:
        print(i)

Let’s take a minute to see what we did here. In order to check whether a number is a multiple of 3, we are using the modulo with the symbol %.We are doing the same thing for multiples of 5. Finally, if the number is neither a multiple of 3 nor 5, we simply display it.

This way we get exactly what we want !… Except when a number is a multiple of both 3 and 5. When that happens, the words Fizz and Buzz are not displayed on the same line ! We shall then take into account this case by adding a new condition, and prevent the first two if to trigger.

for i in range(1, 101):
    if i % 3 == 0 and i % 5 != 0:
        print('Fizz')
    if i % 5 == 0 and i % 3 != 0:
        print('Buzz')
    if i % 3 == 0 and i % 5 == 0:
        print('FizzBuzz')
    if i % 3 != 0 and i % 5 != 0:
        print(i)

This finally works! But at what cost? This whole code is a mess. And it is by no means a piece of code that can easily be maintained. Take this issue as an example: what would happen if we now want to display the word Fizz for multiples of 2 instead of 3? We will have to change this value at 4 different places through the code to make it work.

This might look trivial with such a minimalistic code, but imagine what would happen if this happened on a much bigger project. This code is prone to errors, complicates its maintainability and makes it almost impossible to add new features easily.

Let’s try another approach to make this code more elegant! We’ll first declare a variable which will be the value we want to print at the end. We’ll make it an empty string for now. Each time we successfully match a condition, we’ll simply append the corresponding word to the result. At the end, checking if the variable is empty will let us know if we should print it or rather print the number.

This is what we get.

for i in range(1, 101):
    result = ''
    if i % 3 == 0:
        result += 'Fizz'
    if i % 5 == 0:
        result += 'Buzz'
    print(result or i)

It’s already much clearer! Not only did we shrink the number of lines by half, our if checks are now cristal clear and don’t let any rooms for misinterpretation. Plus, we can easily change the value of any of the numbers if we need to without having to look for all its occurrences. Last but not least, if we ever need to add yet another condition for multiples of 7, we’ll simply have to add two new lines without changing the rest of the code!

We can finally see how this simple FizzBuzz test is so interesting. We were able to test one’s ability to use simple algorithmic principles, but also to check his way of thinking when being confronted to a problem, and if he is able to produce a code that takes care of its future.

To make it short, FizzBuzz is a good way to differentiate a developer from a good developer.