Lab 13 - HTTP Requests: Making Requests of Third-Party APIs
Categories:
6 minute read
Learning Objectives
By the end of this lab, you should be able to:
- make requests to a third-party API using PostMan
- make requests to a third-party API using fetch
- handle successful and unsuccessful responses from a third-party API using Promises
Prerequisites
- Install PostMan
- Make a Canvas token (Note: In doing this, you will need a safe place to store a very long string. If you don’t already use a password manager, consider starting. Dr. Stewart loves 1Password, but it costs money. If you’re looking for a free option, consider Bitwarden).
- Go to your user settings in Canvas
- Scroll Down to the bottom of the “Approved Integrations” section and click the “+ New Access Token” button
- Give your token a name (e.g. “CS343 Demo Token”)
- Probably give a very short expiration like tomorrow since this is easy to create and you can always make another
- Click “Generate Token”
- Copy the token and store it in a safe place (e.g. password manager. Canvas will not show it to you again. If you don’t store it now you’ll have to make a new one.)
Test the Canvas API in PostMan
-
In PostMan, create a new collection named
Canvas
(this is just a way to organize your requests) -
In that collection (
Canvas
), find the (tiny?)Authorization
“tab” and click it and then- set the type to
Bearer Token
- paste in your Canvas token into the
Token
field - press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)
- set the type to
-
Within the Canvas collection, find the (tiny!)
Overview
“tab” and click it. -
Under
Add new
, clickHTTP request
-
Name your request
Get Courses
(in the first field that is focused automatically) -
where the placeholder says
Enter URL or paste text
, paste inhttps://canvas.jmu.edu/api/v1/courses
-
press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)
-
confirm that this request’s
Authorization
“tab” (so tiny!) has its type set toInherit auth from parent
Headers
“tab” (so tiny!)- (click
Hidden
first 🤦♂️) shows (among others) anAuthorization
key with valueBearer YOUR_TOKEN_HERE
- (click
-
press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)
-
press the blue
Send
button -
In the bottom half of PostMan (the Response section), you should soon see something like the following (a JSON array of all your current and past courses)
It's a bit long, does this thing make it a little easier to scroll past after a quick inspection?
[ { "id": 1997199, "name": "343 - S24 - Stewart", "account_id": 81707, "uuid": "FMElx6J6xp5QYV1k2dVyzyuRtbFbo5epwcnO7WeL", "start_at": null, "grading_standard_id": null, "is_public": false, "created_at": "2023-10-12T10:17:04Z", "course_code": "CS343S24", "default_view": "modules", "root_account_id": 81707, "enrollment_term_id": 7536, "license": "private", "grade_passback_setting": null, "end_at": null, "public_syllabus": true, "public_syllabus_to_auth": false, "storage_quota_mb": 15000000, "is_public_to_auth_users": false, "homeroom_course": false, "course_color": null, "friendly_name": null, "apply_assignment_group_weights": true, "calendar": { "ics": "..." }, "time_zone": "America/New_York", "blueprint": false, "template": false, "sis_course_id": "CS343_0001_SP24", "integration_id": null, "enrollments": [ { "type": "teacher", "role": "TeacherEnrollment", "role_id": 3374, "user_id": 5480485, "enrollment_state": "active", "limit_privileges_to_course_section": false } ], "hide_final_grades": false, "workflow_state": "available", "course_format": "on_campus", "restrict_enrollments_to_course_dates": true }, { "id": 1997223, "name": "347 - S24 - Stewart", "account_id": 81707, "uuid": "JWACwAeAmipqP03wjlxJM3rF5FMzlEy1YLW6mtIk", "start_at": null, "grading_standard_id": null, "is_public": false, "created_at": "2023-10-12T10:17:05Z", "course_code": "CS347S24", "default_view": "modules", "root_account_id": 81707, "enrollment_term_id": 7536, "license": "private", "grade_passback_setting": null, "end_at": null, "public_syllabus": true, "public_syllabus_to_auth": false, "storage_quota_mb": 15000000, "is_public_to_auth_users": false, "homeroom_course": false, "course_color": null, "friendly_name": null, "apply_assignment_group_weights": true, "calendar": { "ics": "..." }, "time_zone": "America/New_York", "blueprint": false, "template": false, "sis_course_id": "CS347_0002_SP24", "integration_id": null, "enrollments": [ { "type": "teacher", "role": "TeacherEnrollment", "role_id": 3374, "user_id": 5480485, "enrollment_state": "active", "limit_privileges_to_course_section": false }, { "type": "teacher", "role": "TeacherEnrollment", "role_id": 3374, "user_id": 5480485, "enrollment_state": "active", "limit_privileges_to_course_section": false } ], "hide_final_grades": false, "workflow_state": "available", "course_format": "on_campus", "restrict_enrollments_to_course_dates": true } ]
Test the Canvas API in the Browser via JavaScript
Canvas Tab
- open a tab to JMU’s Canvas (any page, perhaps you still have the settings tab open?) and login.
- open the browser’s developer tools and go to the javascript console
- paste in the following code and press enter:
const responsePromise = fetch('https://canvas.jmu.edu/api/v1/courses', { headers: { Authorization: 'Bearer YOUR_TOKEN_HERE' } });
- once you do that you should see just
<- undefined
⚠️ Initializers in js evaluate to undefined
In Javascript variable declaration initializers (e.g. for const), unlike assignment operators, returnundefined
. This is why you seeundefined
after running the code above. - As you saw in the reading, the
fetch
function from the browser’s Fetch API makes an HTTP request (represented in Javascript as a Request object) and (immediately) returns a Promise that will resolve to a(n HTTP) Response object when a response is received for the request. Use thethen
method on the Promise to handle the successful response. A very common way to handle responses to API calls like this one is to parse the response as JSON. Add the following code to the console and press enter to parse the response as json and to log the result of that (also asynchronous) parsing to the console:responsePromise .then(response => response.json()) .then(console.log);
- You should see the same JSON array of courses that you saw in PostMan.
Non-Canvas Tab
- open a tab to a page that’s not Canvas (maybe just use this tab for a quick test?)
- open the browser’s devtools to the javascript console
- press up on the keyboard to get back statement you made in the steps above that fetch from the canvas api
- press enter to run that fetch again, but now in this tab
- you should see an error in the console that says something like the following
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://canvas.jmu.edu/api/v1/courses. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.
Test the RhymeBrain API in PostMan
- In PostMan, create a new collection named
Unauth API Demos
- In that collection (
Unauth API Demos
), find the (tiny?)Overview
“tab” and click it. - Under
Add new
, clickHTTP request
- Name your request
Get Rhymes
(in the first field that is focused automatically) - where the placeholder says
Enter URL or paste text
, paste inhttps://rhymebrain.com/talk?function=getRhymes&word=web
- press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)
- press the blue
Send
button
🌈 This API does not protect against CORS
So you should be able to test it in any browser window you want, or by dropping the necessary code into your own site:
fetch('https://rhymebrain.com/talk?function=getRhymes&word=web')
.then(response => response.json())
.then(console.log);
Test some other API
- Find an API that you’re interested in (e.g. one from the list on the Final Project Page and try it out in PostMan and in Javascript in your browser’s devtools Javascript console.
- e.g. Dog Facts