Filtering and Rest APIs

 

Concepts in Focus

  • Get Books API
    • Filtering Books
  • REST APIs
    • Why Rest Principles?
    • REST API Principles

1. Get Books API

Let's see how to add Filters to Get Books API

1.1 Filtering Books

  • Get a specific number of books
  • Get books based on search query text
  • Get books in the sorted order

1.1.1 Get a specific number of books

To get specific number of books in certain range we use limit and offset.

Offset is used to specify the position from where rows are to be selected.

Limit is used to specify the number of rows. and many more... Query parameters starts with ? (question mark) followed by key value pairs separated by & (ampersand)

Example :

http://localhost:3000/books/?limit=2
http://localhost:3000/books/?offset=2&limit=3
http://localhost:3000/authors/20/books/?offset=2
Note
  • The query parameters are used to sort/filter resources.

  • The path parameters are used to identify a specific resource(s)

1.1.2 Get books based on search query text

We provide query text to search_q key

search_q = potter

1.1.3 Get books in the sorted order

We provide sorted order to order key

Ascending: ASC DESCENDING: DESC

order = ASC
order = DESC

Filtering GET Books API

app.get("/books/", async (request, response) => {
const {
offset = 2,
limit = 5,
order = "ASC",
order_by = "book_id",
search_q = "",
} = request.query;
const getBooksQuery = `
SELECT
*
FROM
book
WHERE
title LIKE '%${search_q}%'
ORDER BY ${order_by} ${order}
LIMIT ${limit} OFFSET ${offset};`;
const booksArray = await db.all(getBooksQuery);
response.send(booksArray);
});
JAVASCRIPT
Collapse
Note

We can skip or add slash while appending query parameters to the URL

http://localhost:3000/books/?offset=2&limit=3
is same as
http://localhost:3000/books?offset=2&limit=3

2. REST APIs

REST: Representational State Transfer

REST is a set of principles that define how Web standards, such as HTTP and URLs, are supposed to be used.

2.1 Why Rest Principles?

Using Rest Principles improves application in various aspects like scalability, reliability etc

2.2 REST API Principles

  • Providing unique ID to each resource
  • Using standard methods like GET, POST, PUT, and DELETE
  • Accept and Respond with JSON

    and many more...

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form