In this video, we learn how to use the httr2 package to interact with APIs using R. If you've never used an API before, don't worry -- we'll learn about access tokens, response headers, types of requests, and response bodies! We'll put it all into practice by going through a couple of different real-world examples (more specifically, we'll use the OpenAI API to generate images, and we'll use the GitLab API to access project issues and milestones).
! IMPORTANT:
Hadley Wickham suggested some awesome improvements to the code featured in this video. Please use the code on GitHub rather than what's in the video :) Link to the code that should be used: https://github.com/melissavanbussel/YouTube-Tutorials/blob/main/httr2/httr2_examples.R
The changes are:
- Using the req_url_path_append() function rather than pasting things together with the paste0() function
- Define the access tokens as system environment variables and access them using Sys.getenv() rather than including the tokens directly in the script (for instructions on how to set your Open AI API key as a system environment variable, check this video here at timestamp 30:34 - https://youtu.be/tqfOgWr0PAY?si=GEERk28_m4tyDXab&t=1835)
- Using the req_auth_bearer_token() function to greatly simplify working with access tokens
Other resources:
How to get set up with the chattr package to use the OpenAI API in RStudio: https://www.youtube.com/watch?v=t7NrkAeosog
Want to connect?
💼 LinkedIn: https://www.linkedin.com/in/melissavanbussel/
🐦 Twitter: https://twitter.com/melvanbussel
🌐 Website: https://www.melissavanbussel.com/
💻 GitHub: https://github.com/melissavanbussel
☕Buy me a coffee: https://ko-fi.com/melissavanbussel
*Please note: it’s helpful for me if you send me a message on LinkedIn when you add me letting me know you’re adding me because of YouTube, so that I can keep track of how I know each person in my network😊
00:00 What will we learn in this video?
01:38 Creating access tokens
04:48 What is the httr2 package?
05:19 Base URLs
06:01 Endpoints
08:29 Forming the request
08:58 Headers
11:56 GET vs. POST
13:28 Performing the request
14:11 Making sense of the results