Web API

Pages

Recipes

  • One exception to the use nouns instead of verbs rule when designing routes are actions like: translate, compute, convert. All non-resource actions which remind of some non-rest service should use verbs instead of nouns, e.g. http://mybank.com/convert?from=EUR&to=SGD&amount=100.
  • samples of bad design, /getAccount, /createFolder, /updateGroup, /verifyEmail, /searchGroupsByName
  • fundamentally there are two types of resources: collection & instance
  • media types control format specification handles content negotiation and parsing rules, by use of headers:
    • requests: Accept. Samples: Accept:application/json, text/plain, applications/myResourceExtension.csv, Accept: application/myapp.v1.customer.json or Accept: vnd.myapp.v1.customer (versioning with content negotiation)
    • response: Content-Type in the form <content-type>: <media-type>;<options>, like Content-Type: text/html; charset=ISO-8859-4 or Content-Type: application/json or Content-Type: application/foo+json or Content-Type: multipart/form-data; boundary=something
  • Better linking with hateoas, instead of just resource urls specify media type too: 200 OK GET /accounts/x7y8z9

      {
          meta: {
              href: 'https://api.andrei.com/v1/accounts/x7y8z9',
              mediaType: 'application/ion+json;version=2&schema=...'
          }
      }
    
  • reference expansion / entity expansion / link expansion / partial representation: GET /accounts/x7y8z9?expand=someNode, GET /accounts/x7y8z9?fields=name,surname,directory(name)
  • as descriptive as possible, as much info, devs are customers, e.g. POST /dirs 409 CONFLICT
{
    status: 409,
    code: 40924,
    property: 'name',
    message: 'A directory called "Avengers" already exists',
    dev: 'A directory called "Avengers" already exists. If you have a stale cache, expire it.',
    info: 'http://www.andrei.com/docs/api/errors/40924'
}
  • Avoid sessions when possible. Authenticate every request if necessary. Stateless Authorize based on resource content, NOT URL! Use Existing Protocol: Oauth 1.0a, Oauth2, Basic over SSL only. Custom Authentication Scheme: Only if you provide client code / SDK Only if you really, really know what you‟re doing. Use API Keys instead of Username/Passwords.
  • 401 Unauthorize means UNAUTHENTICATED no valid credentials, while 403 Forbidden means UNAUTHORIZED no rights
  • HTTP Authentication Schemes
    • Server response to issue challenge: WWW-Authenticate. Format: WWW-Authenticate: <scheme name> realm=<application name>. Schemes: Basic, Bearer, Digest, OAuth.
    • Client request to submit credentials: Authorization. Format: Authorization: <scheme name|type> <data|credentials>, e.g. Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l where string is base64 encoded from the username and the password are combined with a colon (aladdin:opensesame).
  • Content Negotiation in ASP.NET Core 2.0

Unvisited Queue