Home > database >  How to model the Rest API URL
How to model the Rest API URL

Time:05-03

There is a model that represents a Book.

class Book {
    String author;
    String isbn;
    String releaseDate;
}

I would like to create an API that returns a list of isbn for books whose release date is the provided one by the user. What how this URL should look like?

CodePudding user response:

Create a generic search API.

URI:

GET /api/v1/books/search

Query Parameters:

Param Name Optional Default Value Accepted Values
releaseDate Yes Valid Date in dd/MM/yyyy format
author Yes Any string
isbn Yes Any string
profile Yes Basic Basic, Detailed
page Yes 1 Any integer > 0
size Yes 10 Any integer > 0

Response codes:

200 OK - Successful
500 INTERNAL SERVER ERROR - Exception occurred
400 Bad Request - Bad Request

Response Body:

When profile is Basic return few keys of Book object:

[
  {
    "isbn", "<VALUE>"
  }
]

When profile is Detailed return all keys of Book object:

[
  {
    "author": "<VALUE>",
    "isbn": "<VALUE>",
    "releaseDate": "<Date>"
  }
]

Example:

URL:

https://example.com/api/v1/books/search?isbn=978-3-16-148410-0&profile=Basic

CodePudding user response:

What how this URL should look like?

The URL can look any way you like, provided that it is consistent with the production rules defined in RFC 3986.

You'll probably want a range of resource identifiers, where the resources vary by release date alone. That suggests that you want to use an identifier pattern that you can describe using a URI template.

If users interact with your resources using a web browser, then you'll likely want URI that work the way that HTML forms expect, with application/x-www-form-urlencoded key value pairs as the query part.

For long lived resources, you'll want URI that doesn't need to change - see this guidance from TBL in 1998

But beyond simple mechanical rules like these, the machines don't care what spelling conventions you use -- so you should choose spellings that make the life easier for some humans you care about (ie: choosing a spelling that meets the needs of OPS reviewing an HTTP access log, or choosing a spelling that is easy to document, or choosing a spelling that is easy to recognize in a browser history....)


For the release date part, you'll probably want the date fields to match one of the ISO 8601 formats; for example, see the documentation for java.time.format.DateTimeFormatter.

If the HTML use case is important, then make sure you review date inputs.

CodePudding user response:

Considering you are using spring & rest so here what I am thinking :

@RestController(value="/getBooks")
public class Controller{

@GetMapping(value="/getIsbn")
public List<String> getIsbn(@RequestParam String releaseDate){
 ..
}
}

And your URL would look like(considering you are parsing YYYY-MM-DD date format) with GET:

   https://<your context root>/getBooks/getIsbn&releaseDate=2022-05-03
  • Related