API
This module includes the basic boilerplate for interacting with RESTful API's. The idea is that by following standard REST principles we will always end up with the same url patterns. The only difference is the name of each seperate endpoint.
api.js implements the following HTTP request methods
E.g.: Using cars as resource
Resource | GET | POST | PUT | PATCH | DELETE |
---|---|---|---|---|---|
/cars | Read | Create | Update/Replace | Update/Modify | Delete |
/cars/711 | Read | 405 | Update/Replace | Update/Modify | Delete |
Furthermore api.js abides to these standard REST principles
- Use nouns but no verbs
- GET method and query parameters should not alter the state
- Use plural nouns
- Use sub-resources for relations
- Use HTTP headers for serialization formats
Using the API class
Any class interacting with an RESTful API endpoint extends the API class. The API includes a method for each of the request methods mentioned above.
Example
class Car extends API {}
> const car = new Car()
> car.name
'cars'
> car.construct_url()
'/cars/'
> car.post({'color': 'green'})
POST /cars/ (data {'color':'green'})
Interacting with data
A class that inherits from the API class can be initialized with an id
Example
> const car = new Car(1, fetch=true)
GET /cars/1/
By setting fetch to true the constructor will attempt to fetch the data with a simple GET request.
Now the attributes of car with id 1 are available through the object variable.
> car.object.color
'green'
Sub-resources
Sub resources are created by further subclassing the class which inherits from the API class.
Example
class Ticket extends Car {}
> const ticket = new Ticket(2, car, fetch=true)
> ticket.object.extra_info
'Some extra information about the ticket'
> ticket.parent.object.color
'green'
/** Update information */
> ticket.object.extra_info = 'no info'
> ticket.patch()
PATCH /cars/1/tickets/2/
> ticket.post({'extra_info':'blah'})
405 METHOD NOT ALLOWED
If we are working with instances we need to clear the class in order to be able to post again
> ticket.clear()
> ticket.post({'some':'data'})
POST '/cars/1/tickets/'