RESTAPI
RESTAPI
RESTAPI
REST API
Rules of REST APIs, API patterns, Typical
CRUD operations
Rules for a REST API
• Recall:
o REST – Representational State Transfer
• Standards:
REST APIs have an associated set of standards
o Generally best to stick to them
o You’re doing things the right way if you decide to make your API public
Request URLs
• Request URLs for a REST API have a simple standard
o Think about your DB collections
o Each URL in a set will have the same basic path, and some may have
additional parameters
Create new
contact POST /contacts /api/contacts
Read list of
contact GET /contacts /api/contacts
Read specific
contact GET /contacts contactid /api/contacts/123abc
Update specific
contact PUT /contacts contactid /api/contacts/123abc
Delete specific
contact DELETE /contacts contactid /api/contacts/123abc
API URLs for
subdocuments
• Subdocuments are treated in a similar way, but
require an additional parameter
• E.g.:
o Action: Create a new review for a product
o Method: POST
o URL: /api/products/123/reviews/abd
Responses and status
code
• If you make a request, a good API will always respond
and not leave you hanging
o A null response
10 Most popular status
codes
• A good REST API should return the correct HTTP
status code
Status Code Name Use case
200 OK A successful GET or PUT request
201 Created A successful POST request
204 No Content A successful DELETE request
n unsuccessful GET, PUT, or POST
400 Bad Request request due to invalid content
Requesting a restricted URL with invalid
401 Unauthorized credentials
403 Forbidden Making a request that isn't allowed
Unsuccessful request due to invalid
404 Not Found parameter in URL
Request method not allowed for given
405 Method not allowed URL
Unsuccessful POST request when
another object with the same data
409 Conflict already exists
500 Internal server error Problem with the server or DB server
Setting up API in express
• We’ve already got a good idea about the actions
we want our API to perform, and the URL paths
needed to do so
• In controller:
o Return JSON and response status code from an Express request
Product
.findById(req.params.productid)
.select('name reviews')
.exec(
function(err, product) { // do error checking-product
var review;
review = product.reviews.id(req.params.reviewid);
// do error checking for review
} );
Resources
• http://www.restapitutorial.com/httpstatuscodes.html