Thursday, May 2, 2019

General API coding guidelines

Its always advisable to follow suggested guidelines while writing APIs (can be violated for really good reason).
  1. Keep action method thinnest possible (How about 5-10 lines?). Having large method indicates that you are writing logic in action method which is not expected.
  2. Avoid writing validation code inside action method. Alternately, use data annotations, write Validate() method separate inside model/request class or write separate validator classes.
  3. Avoid writing any logic in action methods. Alternately, move logic to layer down the line (maximum times a business logic layer). Writing logic in action method reduces re-usability of logic because action methods are leaf methods.
  4. Return proper http response code
  5. Use correct http methods/verbs
  6. Cache your GET APIs wherever possible
  7. Do not write anonymously accessible APIs. Use Basic authentication, OAuth2, Token based authentication or at least use API keys
  8. Do not at all expose sensitive data in query or route. Encrypt the data and send through request body or request header
  9. Always use versioning in routes. This helps to introduce latest logic for same api keeping old one intact and you can provide enough time to clients to shift to new version by deprecating older one.
  10. Keep target to return response in less than 300 milliseconds. Post, Put, Delete can happen in 10-50 milliseconds too.
  11. Avoid returning large lists, use paging instead. Multiple requests on server work more efficiently than single long running request.
  12. You must deploy API sites with SSL security to avoid Man In The Middle (MITM) attacks. 

No comments:

Post a Comment