
Bonus - Complete CRUD API Example
This is a bonus section. You will learn how to create a complete CRUD API. CRUD means Create, Read, Update and Delete.
Note: This section does not have a video tutorial. Follow the steps below to build a complete Articles API.
What you will build
You will create an Articles API with these operations:
GET - Get all articles
GET - Get one article by ID
POST - Create a new article
PUT - Update an article
DELETE - Delete an article
How it works
The flow is: routes → controllers → services → models (Sequelize) → MySQL database
Step 1 - Update routes
We will create 5 routes in the article router. Each route calls a controller function.
import { FastifyInstance } from "fastify";
import articleController from './../controllers/article.controller';
const articleRouter = async (app: FastifyInstance) => {
// GET all articles
app.get(
"/",
articleController.handleGetArticle
);
// GET one article by ID
app.get(
"/get/:id",
articleController.handleGetArticleById
);
// POST create a new article
app.post(
"/create",
articleController.handleCreateArticle
);
// PUT update an article
app.put(
"/update/:id",
articleController.handleUpdateArticle
);
// DELETE delete an article
app.delete(
"/delete/:id",
articleController.handleDeleteArticle
);
};
export default articleRouter;Step 2 - Create request types
We need to define types for the request data. This helps TypeScript understand what data to expect.
Create a new file called article.controller.types.ts inside src/types/articles.
import { FastifyRequest } from "fastify";
export type RequestWithIdArticle = FastifyRequest<{
Params: { id: string };
}>;
export type UpdateArticleRequest = FastifyRequest<{
Params: { id: string };
Body: {
title?: string | undefined;
text?: string | undefined;
type?: string | undefined;
};
}>;
export type ArticleCreateRequest = FastifyRequest<{
Body: {
title?: string | undefined;
text?: string | undefined;
type?: string | undefined;
};
}>;Step 3 - Update controllers
In the article controller, we will create handler functions. Each function calls a service function.
import { ArticleCreateRequest, RequestWithIdArticle, UpdateArticleRequest } from "types/articles/article.controller.types";
import { ArticleAttributes } from "types/articles/article.model.types";
import { articleService } from "../services";
export const handleGetArticle = async () => {
return articleService.getArticles()
}
export const handleGetArticleById = async (req: RequestWithIdArticle) => {
const id = req.params.id;
return articleService.getOneArticle(id)
}
export const handleCreateArticle = async (req: ArticleCreateRequest) => {
const { title, text, type } = req.body
return articleService.createArticle({ title, text, type })
}
export const handleUpdateArticle = async (req: UpdateArticleRequest) => {
const { title, text, type } = req.body
return articleService.updateArticle(req.params.id, { title, text, type })
}
export const handleDeleteArticle = async (req: RequestWithIdArticle) => {
return articleService.deleteArticle(req.params.id)
}
export default {
handleGetArticle,
handleGetArticleById,
handleCreateArticle,
handleUpdateArticle,
handleDeleteArticle
}Step 4 - Update services
In the article service, we create functions that use Sequelize to interact with the database.
import { ArticleAttributes } from "types/articles/article.model.types";
import db from "../models";
const ArticleModel = db.Article
export const getArticles = async (): Promise<ArticleAttributes[]> => {
const response = await ArticleModel.findAll();
return response
}
export const getOneArticle = async (id: string): Promise<ArticleAttributes> => {
const response: ArticleAttributes = await ArticleModel.findByPk(id)
return response
}
export const createArticle = async (body: ArticleAttributes): Promise<ArticleAttributes> => {
const response: ArticleAttributes = await ArticleModel.create(body)
return response
}
export const updateArticle = async (id: string, body: ArticleAttributes) => {
const response = await ArticleModel.update({ ...body }, { where: { id } })
return response
}
export const deleteArticle = async (id: string) => {
const response = await ArticleModel.destroy({ where: { id } });
return response
}
export default {
getArticles,
getOneArticle,
createArticle,
updateArticle,
deleteArticle
}Step 5 - Test your API
Now you can test all the routes using Thunder Client. Here are examples of the results:
GET all articles
Visit GET http://localhost:5000/api/v1/articles to get all articles:
GET one article
Visit GET http://localhost:5000/api/v1/articles/get/:id to get one article (replace :id with an article ID):
CREATE article
Send a POST request to http://localhost:5000/api/v1/articles/create with article data in the body:
UPDATE article
Send a PUT request to http://localhost:5000/api/v1/articles/update/:id with updated data in the body:
DELETE article
Send a DELETE request to http://localhost:5000/api/v1/articles/delete/:id to delete an article:
Congratulations! You now have a complete CRUD API working with a database!
Originally published by me at the dev to - Akkarapon Phikulsri on DEV Community.







