Skip to content

Instantly share code, notes, and snippets.

@popdemtech
Created December 20, 2022 06:27
Show Gist options
  • Select an option

  • Save popdemtech/df211ed72ccafdbe840c704092b9596c to your computer and use it in GitHub Desktop.

Select an option

Save popdemtech/df211ed72ccafdbe840c704092b9596c to your computer and use it in GitHub Desktop.
Web Component which makes an API call and renders the response on screen 😎
<html>
<head>
<!-- This file defines a web component APICard/api-card -->
<!-- which, when given an JSON returning route, -->
<!-- renders the response returned by the route -->
<!-- or the error message returned by the route -->
<!-- in a graphical, user-friendly way -->
</head>
<body>
<!-- Using the api-card component -->
<api-card route="/api/ping"></api-card>
<api-card route="/api/health"></api-card>
<api-card route="https://gist.githubusercontent.com/popdemtech/83d9430bafd2b968b6b8a74ecc19734a/raw/52a4c3382db9182277403cf112303e4c4d257d93/json.json"></api-card>
<script>
class APICard extends HTMLElement {
constructor() {
super();
}
async connectedCallback() {
this.route = this.getAttribute('route');
await fetch(this.route).then((response) => response.json())
.then((data) => {
this.response = JSON.stringify(data, null, 2);
})
.catch((e) => {
this.response = e.message;
});
this.render();
}
render() {
this.innerHTML = `
<div class="api-card">
<p><b>${this.route}</b></p>
<pre style="background-color:#ddd;padding:10px;width:fit-content;">${this.response}</pre>
</div>
<hr>
`;
}
}
customElements.define("api-card", APICard);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment