Menu

Prototype an API call before you write the client
📰

Prototype an API call before you write the client

DEV Community: typescript·JSLab·7 days ago
#JqdlQ7nI
#devtotypescript#devto#dev#token#headers
Reading 0:00
15s threshold

Before writing a client for an API, I want answers: what does the response actually look like, what happens without a token, what are the limits? A scratch file gets those answers faster than reading the docs twice.

Our test subject: the GitHub REST API, which works without a token (with a low rate limit) and with one.

Step 1: the token comes from the environment

Never paste a token into code, even scratch code. It ends up in a screenshot, a gist or a commit.

const token = process . env . GITHUB_TOKEN ;

Enter fullscreen mode

Exit fullscreen mode

In Node and Bun, process.env holds the environment the process started with. undefined here is a valid state, and the code should handle it.

Step 2: a request that fails properly

const res = await fetch ( "https://api.github.com/repos/oven-sh/bun" , { headers : { Accept : "application/vnd.github+json" , . . . ( token ? { Authorization : `Bearer ${token}` } : { } ) , } , signal : AbortSignal . timeout ( 5000 ) , } ) ;

if ( ! res .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.