Reading API documentation
Pay attention to seven things when you read an API.
- Authentication
- CORS
- JSONP
- Pagination
- Content types
- API Versions
- Rate limits
Authentication
Do you need to authenticate yourself to use an API? If yes, how do you perform the authentication?
Do you need to sign up for their service first?
Do you need an API key?
Do you use basic authentication?
Do you need OAuth?
This information will tell you if it’s possible to send requests through your browser. If you need to protect your credentials, you’ll have to authenticate through a server.
CORS support
You can only send requests through a browser if the API supports CORS. If they don’t support cross-origin requests, you’ll get a No Access-Control-Allow-Origin
error.
If the API doesn’t support CORS, you’ll have two ways to make a request:
- Send it through a server
- Use JSONP
JSONP support
If an API supports JSONP, they’ll talk about JSONP. If they don’t support JSONP, you won’t find it.
When you request for a list of items, many APIs respond with an incomplete list. For example, Github sends you 30 repositories even if the user has more than 30 repositories.
How can you request for more items at once?
You’ll learn more about pagination in the advanced asynchronous JavaScript module.
Content Types
What content should you expect from the server? Are you expecting JSON? Are you expecting something else? This will affect how you handle the response.
When you send a request, pay attention to the content type the server expects. This is usually written in the introduction. If you can’t find it in the introduction, look for a Content-Type
header for the endpoint.
API Versions
You can specify which version of an API to request for. If you did not specify a version, APIs will point you to the latest stable version.
It’s helpful to specify a version because different versions require different code. If APIs direct you to a different version, your code will break for seemingly no reason.
There are two ways to specify an API version:
- In the endpoint
- In a request header
Twitter uses the first method. You can see Twitter’s API is at version 1.1 through its endpoint.
https://api.twitter.com/1.1/account/settings.json
Github uses the second method. To tell Github to use version 3 (the current version), you need to set an Accept
header.
fetch ('https://api.github.com', {
headers: { 'Accept': 'application/vnd.github.v3+json' }
})
Rate limits
Rate limits will tell you how many requests you can send per hour or per day. This will help you plan for your requests.