How to create an API wrapper using a JavaScript proxy
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
I just found a super smart gist from David Wells that's worth bookmarking.
David uses a JavaScript Proxy
to map object properties to fetch
calls.
This approach works quite nice for querying RESTful APIs. apiObject
maps to /cars/
and apiObject
maps to /cars/123/
. 👏
// Found at https://gist.github.com/DavidWells/53518b3c12344952641dc81cc7599939
const createApi = (url) => {
return new Proxy({}, {
get(target, key) {
return async function(id = "") {
const response = await fetch(`${url}/${key}/${id}`)
if (response.ok) {
return response.json();
}
return Promise.resolve({ error: "Malformed Request" })
}
}
})
}
let api = createApi("https://swapi.co/api")
// 'get' request to https://swapi.co/api/people
let people = await api.people()
// 'get' request to https://swapi.co/api/people/1
let person = await api.people(1)
What a great little trick! 💯
Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 12 days ago.
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 12 days ago.
Related Topics
Related Articles
- A new method to validate URLs in JavaScript (2023 edition)
- How to remove all event listeners from a DOM element
- Copy an array and replace one element at a specific index with modern JavaScript
- How to prerender Tweets without using the official Twitter APIs
- How to use EventTarget as a web-native event emitter