Sample REST endpoint
Create api endpoint /products with pagination and fetch data from database
Categories:
Lets create GET /products api endpoint with pagination. Products are stored in mysql or postgres database
Database structure for products table
create table product
(
id int auto_increment
primary key,
name varchar(300) not null,
price int default 0 not null,
available tinyint(1) null,
image varchar(300) null,
available_quantity int default 0 not null
)
charset = utf8mb3;
Create file ./rest/products.json
{
"path": "/products",
"methods": [
"GET"
],
"query": "products-paginated",
"authorized": false
}
Create file ./queries/products-paginated.json
{
"type": "sql-select-paginated",
"id": "products-paginated",
"connection": "sample-database-connection",
"query": "SELECT * FROM `product` limit :offset, :limit",
"queryCount": "SELECT count(*) as c FROM `product`",
"params": [
{
"name": "limit",
"type": "int",
"default": 10,
"required": true
},
{
"name": "page",
"type": "int",
"default": 1,
"required": true
}
]
}
Two files later you are able to fetch your paginated products by calling endpoint below
GET http://localhost:8080/products?page=1&limit=10
{
"results": [
{
"available": 1,
"available_quantity": 10,
"id": 1,
"image": "/images/shoes.jpng",
"name": "Shoes",
"price": 10000
},
{
"available": 1,
"available_quantity": 2,
"id": 2,
"image": "/images/t-shirt.jpng",
"name": "T-Shirt",
"price": 1000
}
],
"count": 2,
"pages": 1,
"page": 1
}
Response lime for localhost is approximately 3ms
Last modified April 16, 2024: content fix (a2d9b96)