Lab 13 - HTTP Requests: Making Requests of Third-Party APIs

Work with PostMan and Promises (via fetch) to make requests to third-party API.

Learning Objectives

By the end of this lab, you should be able to:

  1. make requests to a third-party API using PostMan
  2. make requests to a third-party API using fetch
  3. handle successful and unsuccessful responses from a third-party API using Promises

Prerequisites

  1. Install PostMan
  2. 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).
    1. Go to your user settings in Canvas
    2. Scroll Down to the bottom of the “Approved Integrations” section and click the “+ New Access Token” button
    3. Give your token a name (e.g. “CS343 Demo Token”)
    4. Probably give a very short expiration like tomorrow since this is easy to create and you can always make another
    5. Click “Generate Token”
    6. 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

  1. In PostMan, create a new collection named Canvas (this is just a way to organize your requests)

  2. In that collection (Canvas), find the (tiny?) Authorization “tab” and click it and then

    1. set the type to Bearer Token
    2. paste in your Canvas token into the Token field
    3. press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)
  3. Within the Canvas collection, find the (tiny!) Overview “tab” and click it.

  4. Under Add new, click HTTP request

  5. Name your request Get Courses (in the first field that is focused automatically)

  6. where the placeholder says Enter URL or paste text, paste in https://canvas.jmu.edu/api/v1/courses

  7. press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)

  8. confirm that this request’s

    1. Authorization “tab” (so tiny!) has its type set to Inherit auth from parent
    2. Headers “tab” (so tiny!)
      1. (click Hidden first 🤦‍♂️) shows (among others) an Authorization key with value Bearer YOUR_TOKEN_HERE
  9. press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)

  10. press the blue Send button

  11. 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

  1. open a tab to JMU’s Canvas (any page, perhaps you still have the settings tab open?) and login.
  2. open the browser’s developer tools and go to the javascript console
  3. paste in the following code and press enter:
    const responsePromise = fetch('https://canvas.jmu.edu/api/v1/courses', {
        headers: {
            Authorization: 'Bearer YOUR_TOKEN_HERE'
        }
    });
    
  4. once you do that you should see just <- undefined
  5. 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 the then 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);
    
  6. You should see the same JSON array of courses that you saw in PostMan.

Non-Canvas Tab

  1. open a tab to a page that’s not Canvas (maybe just use this tab for a quick test?)
  2. open the browser’s devtools to the javascript console
  3. press up on the keyboard to get back statement you made in the steps above that fetch from the canvas api
  4. press enter to run that fetch again, but now in this tab
  5. 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

  1. In PostMan, create a new collection named Unauth API Demos
  2. In that collection (Unauth API Demos), find the (tiny?) Overview “tab” and click it.
  3. Under Add new, click HTTP request
  4. Name your request Get Rhymes (in the first field that is focused automatically)
  5. where the placeholder says Enter URL or paste text, paste in https://rhymebrain.com/talk?function=getRhymes&word=web
  6. press your OS’s hotkey for saving (e.g. command + s on macOS and ctrl + s in all other OSes)
  7. press the blue Send button

Test some other API

  1. 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.