Skip to content

Instantly share code, notes, and snippets.

@markmichon
Created March 9, 2020 02:04
Show Gist options
  • Save markmichon/a4abeae93009232bc5a6cbe463fdbbd7 to your computer and use it in GitHub Desktop.
Save markmichon/a4abeae93009232bc5a6cbe463fdbbd7 to your computer and use it in GitHub Desktop.
Dev.to API client example
const fetch = require("isomorphic-unfetch");
const querystring = require("querystring");
class DevTo {
constructor(config) {
this.api_key = config.api_key;
this.basePath = "https://dev.to/api";
}
request(endpoint = "", options = {}) {
let url = this.basePath + endpoint;
let headers = {
api_key: this.api_key,
"Content-type": "application/json"
};
let config = {
...options,
...headers
};
return fetch(url, config).then(r => {
if (r.ok) {
return r.json();
}
throw new Error(r);
});
}
getArticles(options) {
let qs = options ? "?" + querystring.stringify(options) : "";
let url = "/articles" + qs;
let config = {
method: "GET"
};
return this.request(url, config);
}
getArticleById(id) {
let url = "/articles/" + id;
return this.request(url, {});
}
createArticle(body) {
const options = {
method: "POST",
body: JSON.stringify(body)
};
return this.request("/articles", options);
// Optional: add your own .catch to process/deliver errors or fallbacks specific to this resource
}
}
let api = new DevTo({
api_key: process.env.SECRET
});
api
.getArticles({ username: "bearer", page: 1 })
.then(data => console.log(data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment