View profile

Common Tricks for Talking to REST APIs with Axios

Common Tricks for Talking to REST APIs with Axios
By Mastering JS Weekly • Issue #43 • View online
Making API requests is difficult because every REST API does things a little differently. Between different authorization paradigms, different HTTP request body encodings, different header requirements, it’s easy to get stuck. Here’s some gotchas with some common REST APIs, and how to work around them with Axios.

Slack API
A common gotcha with the Slack API is that only some Slack API calls support JSON. For example, Slack OAuth API calls don’t support JSON. For those requests, you need to send the request body with Content-Type “application/x-www-form-urlencoded”, and send your data in the form “key1=value1&key2=value2”.
Posting form-encoded request bodies with Axios is easy. Just pass a string as the request body, and Axios will automatically set the Content-Type header to “application/x-www-form-urlencoded”.
Sending a POST request with a form-encoded body in Axios
Sending a POST request with a form-encoded body in Axios
Mailgun API
Mailgun is a great API for sending emails. Unfortunately, their REST API requires you to authenticate using HTTP basic auth. Your Mailgun API key isn’t enough.
To authenticate with the Mailgun API, you need to pretend your username is “api” and your password is your API key. Thankfully, Axios has built-in support for basic auth using the `auth` option. Here’s how you can make a request to the Mailgun API with Axios:
HTTP Basic Auth with Axios is easy
HTTP Basic Auth with Axios is easy
Moving On
Different APIs have different encodings, authentication requirements, and other odd details. Axios does a good job of making it easy to work around some common sticking points. Axios makes it easy to switch between JSON and form-encoding POST request bodies, which are the two most common encodings for request bodies. It also handles HTTP basic auth, which some APIs require instead of just asking you to put your API key in the authorization header.
New Tutorials
Other Interesting Reads
OAuth in Node.js CLI Apps | www.thecodebarbarian.com
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue