owned this note
owned this note
Published
Linked with GitHub
---
tags: api,practical
---
# Introduction to APIs
In this session, we are going to learn how to use Postman to interact with an API over HTTP.
## Installing Postman
Postman is a REST client, it allows us to interact with an API by building HTTP requests. This is very handy when we are building an API, or are learning how a new one works. One way to think of it is a web browser that doesn't render the web page.
[Download Postman Here](https://www.postman.com/downloads/)
You can find details of the interface [here](https://learning.postman.com/docs/getting-started/navigating-postman/). We recommend you also read the next page [sending your first request](https://learning.postman.com/docs/getting-started/sending-the-first-request/).
## Challenge
We will be using this [api](https://github.com/MCRcodes/api-intro) to get used to sending `GET` and `POST` requests. The aim is to send a `GET` request to receive a question from the api, then send a `POST` request with an answer to the same url. If you answer correctly, you will receive the url to request the next question from.
When you're ready, send a `GET` request to `https://api-introduction.herokuapp.com/fizzbuzz`. You should receive this JSON response:
```json
{
"message":"Thank you for your application to API Inc.\n\nOur automated fizzbuzz interview process will help us determine if you have what it takes.\n\nFor each question, you will GET the question and then give us the answer back to the same URL.\nYou will also find the URL for the next question in the nextQuestion parameter for each response.\n\nThe first question is at https://api-introduction/fizzbuzz/question/1.\n\nGood Luck\n",
"nextQuestion":"/fizzbuzz/questions/1"
}
```
![](https://i.imgur.com/Cq0ISnu.png)
### JSON
The response will be in `JSON` (JavaScript Object Notation), this is a string which can be parsed into an object by most programming languages. It is syntactically similar to an object literal in JavaScript, with two key differences:
- Both the key and the value must be in double quotes
- The last value cannot have a comma after it
In the response, you will see a property called `nextQuestion` with the route to send your next request to. Add this to the end of the base url of `https://api.noopschallenge.com/` and send you next get request.
![](https://i.imgur.com/UdLgba4.png)
## Sending your first POST request
Once you have the next question, we need to build a `POST` request to answer it. To do this you will need to:
1. Set the request type next to the url bar as `POST`, the url should remain the same for answering the question.
1. Click on the `body` tab, select the `raw` option. A dropdown menu will appear to the right, it will be set to `Text` by default. Set it to `JSON`
1. We now need to write the request body, you may have guessed that it needs to be in `JSON`, it should look something like this:
```json=
{
"answer": "YOUR ANSWER HERE"
}
```
![](https://i.imgur.com/OuEJXIC.png)
Once that's in place you should be good to send your first `POST` request.If it worked, you'll get a respnse with a `nextQuestion` property. Hit that with a get request to find out what the next question is.
## Next challenge
![](https://i.imgur.com/mv6tlYP.png)
```json=
{
"message": "FizzBuzz is the name of the game.\nHere's a list of numbers.\nSend me back a string as follows:\nFor each number:\nIf it is divisible by 3, print \"Fizz\".\nIf it is divisible by 5, print \"Buzz\".\nIf it is divisible by 3 and 5, print \"FizzBuzz\".\nOtherwise, print the number.\n\nEach entry in the string should be separated by a space.\n\nFor example, if the numbers are [1, 2, 3, 4, 5], you would send back:\n\n{\n \"answer\": \"1 2 Fizz 4 Buzz\"\n}\n",
"rules": [
{
"number": 3,
"response": "Fizz"
},
{
"number": 5,
"response": "Buzz"
}
],
"numbers": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
],
"exampleResponse": {
"answer": "1 2 Fizz 4 Buzz..."
}
}
```
Okay, so this one is a bit more complicated. There's a few ways you could solve this. You could do it manually, but that defeats the point of learning to code.
Instead dust off your old fizzBuzz kata and throw together a script to construct a string that will answer this question. You could use the console in your browser to do this, or you could open a `node` instance in your command line.
If we want to make things even easier for ourselves, we could take advantage of the fact that Postman has a built in `node` instance. Normally, this is used for running tests on responses from APIs. In this case we can use it to process the data we get from it.
To access it, click on the `Tests` button. Any JavaScript you write here will run after the response returns from your request.
![](https://i.imgur.com/79HWuw4.png)
Postman also has a built-in library called `pm`. It lets us access the data from the response. The numbers that FizzBot wants us to process can be accessed through `pm.response.json().numbers`. We need to call `.json()` on the response in order to convert the JSON string into somthing that JavaScript can understand.
```js
const numbers = pm.response.json().numbers
const fizzBuzz = (number) => {
return number
}
console.log(numbers.map(number => fizzBuzz(number)).join(' '));
```
Right now the we are just returning the numbers joined together in a string. You will need to edit the `fizzBuzz` function to answer the question. You can see the output to the terminal with `window > postman console`
When you're done, copy your answer into a request body and `POST` it back to the url and see if you can get the next question.
## Changing Rules
There will be a few `FizzBuzz` questions, but at some point the rules will change to `BeepBoop`. These rules will be accessible on the response body as an array called `rules`.
```json=
"rules": [
{
"number": 2,
"response": "Beep"
},
{
"number": 5,
"response": "Boop"
}
],
```
While you could re-write your fizzBuzz function to account for the new rules, it would be much better to write a new function that takes a number and a set of rules, and returns the appropriate response. This would future-proof your code against any more rule changes.
Whichever way you decide to move on, you will eventaully recieve a final time and grade:
```json=
{
"result": "interview complete",
"grade": "A+",
"elapsedSeconds": 5,
"message": "Congratulations!\nYou completed the interview in 5 seconds.\nThat was unbelievably fast!\n"
}
```
## Speed Run
Chances are you will have taken quite a bit of time to complete the challenges. Here are some way you could try and automate the process a bit more, and get a better grade:
- Generalise you fizzBuzz function to take advantage of the array of rules you get with each question.
- Next to the `test` tab is a `pre-request script tab`, in here you can write code that runs before your main request. You could use this to write a `GET` request which runs before your main request, builds a request body, and passes it to the main request as a `global variable`.
- Global variables can be set with `pm.globals.set("name", value)`, and accessed with `{{name}}`. Remember that you will need to convert your request body to json with `JSON.stringify(body)`
- You can send a request with `pm.sendRequest(url, (error, response) => {})`
- After your main request runs, set the `nextQuestion` as an environment variable so you can access it ahead of the next request.
Be sure to post your time and grade in the cohort channel!