Build: The Web
💫

JSONPlaceholder - Blog Posts

JSONPlaceholder is a free online REST API that you can use to create fake data anytime you need it. It might be in a GitHub README, a Code Sandbox demo, Stack Overflow code examples, or simply to test things locally.
Add the following code to your index.html.
<!DOCTYPE html> <html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <meta http-equiv="X-UA-Compatible" content="ie=edge" />    <link rel="stylesheet" href="style.css" />    <title>JSON Placeholder</title>  </head>   <body onload="run()">    <h1>Posts</h1>    <main>      <div>        <h3>Title</h3>        <p>Some post content</p>      </div>    </main>     <script src="script.js"></script>  </body> </html>
The body tag has the onload attribute which calls the function “run” once the body fully loads.
Add the following code to your style.css.
@import url("https://fonts.googleapis.com/css2?family=Mukta&display=swap"); * { padding: 0; margin: 0; box-sizing: border-box; font-family: "Mukta", sans-serif; } body { width: 100%; min-height: 100vh; padding: 20px; justify-content: center; align-items: center; } div { padding: 20px; margin: 20px 10px; border: 2px solid black; }
Add the following code to the script.js.
const main = document.querySelector("main"); async function run() { const res = await fetch("https://jsonplaceholder.typicode.com/posts"); if (res.ok) { let json = await res.json(); let html = ""; console.log(json); json.forEach((e) => { let content = ` <div> <h3>${e.title}</h3> <p>${e.body}</p> </div> `; html += content; }); main.innerHTML = html; } }
Select the main tag. In the function run, which is called once the body loads, fetch the api using fetch function.
The fetch() method in JavaScript is used to request the server and load the information in the webpages. The request can be of any APIs that returns the data of the format JSON or XML. This method returns a promise. Syntax: fetch( url, options )
Finally, add the fetched data to the main tag that was selected.
badge