Creating a REST API for Fetching Blog Posts with Express and SQLite
Scenario
We need an Express REST API for retrieving these two blog posts that we will store in an SQLite Database.
blog1 = {
id: 1
title: "The First of Many Blogs",
content: "Welcome to my awesome blog. Prepared to be amazed."
};
blog2 = {
id:2
title: "The Second of Many Blogs",
content: "Amazed yet?"
};
Approach
Project Setup
Create the project directory and initialize the project.
mkdir sqlite-express
cd sqlite-express
npm init -y
Open the project in VSCode.
code .
Dependencies
npm install express sqlite3 cors
Database
Create the file database.js
in the root project directory ( sqlite-express
) with the following content:
Server
Create the file index.js
in the root project directory ( sqlite-express
) with the following content:
Run
Start the server by running node index.js
.
Visit http://localhost:8000/api/blogs
The browser should render the blog posts:
{"message":"success","data":[{"id":1,"title":"The First of Many Blogs","content":"Welcome to my awesome blog. Prepared to be amazed."},{"id":2,"title":"The Second of Many Blogs","content":"Amazed yet?"}]}
Try https://localhost:8000/api/blogs/1
.
You should see:
{"message":"success","data":{"id":1,"title":"The First of Many Blogs","content":"Welcome to my awesome blog. Prepared to be amazed."}}