API design patterns

Key principles and learnings for API design

Sep 1, 2020 4 min read

Update 2022: I’m glad I captured these notes in 2020 for reference in future API design work. But, from 2021-2022, I saw 2-5x faster product development without an API. See this post: A modern app tech stack, built for speed


Principles

Uniform HTTP status error codes

Decision tree for error handling logic MUST be followed:

Error objects

Always in English only, the frontend will be responsible for I18n using the code key to lookup the I18n value:

Standardize data formats

Standardize data formats

date_formats = {
  api_date:     '%F',     # 2020-09-01,          - ISO8601 date
  api_datetime: '%FT%TZ'  # 2018-09-01T04:05:06Z - ISO8601 timestamp - UTC
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats

Serialization of relationships

Filtering

?filter[job_status]=[complete,queued] # job_status of complete or queued
ne = not equals
lt = less than
gt = greater than
lte = less than or equals
gte = greater than or equals

Right Hand Side (RHS) Colon MUST be used to convey additional operators and values for a parameter

?filter[balance]=gt:1000        # filter for balances greater than 1000.

Blueprint for releasing new API endpoints

Each step should be a separate PR to quickly get the changes in to the main branch.

  1. Define RESTful routes + routing specs
  2. Define OpenAPI schema
  3. Define Resource policy + policy specs
  4. Define serializer + serializer specs
  5. Define controller + request specs
Read more posts like this in the Software Engineering Toolbox collection.
Visit homepage
comments powered by Disqus