Debian Codegraph @

www/src/content/essays/why-tend-not-to-use-content-negotiation.md

raw symbols SCIP
1 ---
2 title: "Why I Tend Not To Use Content Negotiation"
3 description: "In this essay, Carson Gross explores his preference for separating JSON and hypermedia APIs instead of using content negotiation, a feature in HTTP that allows clients to request different formats (e.g., HTML, JSON). He discusses the limitations of content negotiation in APIs, especially when mixing stable, versioned JSON data APIs with dynamic, UI-driven hypermedia APIs. Carson argues that by splitting these concerns into distinct APIs, developers can better maintain stability for data APIs while allowing flexibility for hypermedia APIs to evolve with user interface needs. He also highlights the challenges content negotiation introduces to API 01-frontend and scalability."
4 created: 2023-11-18
5 modified: 2023-11-18
6 authors: [ "Carson Gross" ]
7 tags: ["guides"]
8 ---
9
10 I have written a lot about Hypermedia APIs vs. Data (JSON) APIs,
11 including [the differences between the two](/essays/hypermedia-apis-vs-data-apis),
12 what [REST "really" means](/essays/how-did-rest-come-to-mean-the-opposite-of-rest) and why [HATEOAS](/essays/hateoas)
13 isn't so bad as long as your API is interacting with a [Hypermedia Client](/essays/hypermedia-clients).
14
15 Often when I am engaged in discussions with people coming from the "REST is JSON over HTTP" world (that is, the normal
16 world) I have to navigate a lot of language and conceptual issues:
17
18 * No, I am not advocating you return HTML as a general purpose API, hypermedia makes for a bad general purpose API
19 * Yes, I am advocating [tightly coupling](/essays/two-approaches-to-decoupling) your web application to your hypermedia
20 API
21 * No, I do not think that we will ever fix how the
22 industry [uses the term REST](/essays/how-did-rest-come-to-mean-the-opposite-of-rest)
23 * Yes, I am advocating you [split your data API and your hypermedia API up](/essays/splitting-your-apis)
24
25 The last point often strikes people who are used to a single, general purpose JSON API as dumb: why have two APIs when
26 you
27 can have a single API that can satisfy any number of types of clients? I tried to answer that question as best I can in
28 the essay
29 above, but it is certainly a reasonable one to ask.
30
31 It seems like (and it is) extra work in some ways when compared to having one general API.
32
33 At this point in a conversation, someone who agrees broadly with my take on
34 REST, [Hypermedia-Driven Applications](/essays/hypermedia-driven-applications),
35 etc. will often jump in and say something like
36
37 > "Oh, it's easy, you just use _content negotiation_, it's baked into HTTP!"
38
39 Not being content with alienating only the general purpose JSON API enthusiasts, let me now proceed to also alienate
40 my erstwhile hypermedia enthusiast allies by saying:
41
42 *I don't think content negotiation is typically the right approach to
43 returning both JSON and HTML for most applications.*
44
45 ## What Is Content Negotiation?
46
47 First things first, what is "content negotiation"?
48
49 [Content negotiation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation) is a feature of HTTP that
50 allows a client to negotiate the content type of the response from a server. A full treatment of the implementation
51 in HTTP is beyond the scope of this essay, but let us consider the most well known mechanism for content negotiation
52 in HTTP, the [
53 `Accept` Request Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation#the_accept_header).
54
55 The `Accept` request header allows a client, such as a browser, to indicate the `MIME` types that it is willing to
56 accept
57 from the server in a response.
58
59 An example value of this header is:
60
61 ```
62 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8
63 ```
64
65 This `Accept` header tells the server what formats the client is willing to accept. Preferences are expressed via the
66 `q` weighting factor. Wildcards are expressed with asterisks `*`.
67
68 In this case, the client is saying:
69
70 > I would most like to receive text/html, application/xhtml+xml or image/webp. Next I would prefer application/xml.
71 > Finally, I will accept whatever you give me.
72
73 The server then can take this information and determine the best content type to provide to the client.
74
75 This is the act of "content negotiation" and it is certainly an interesting feature of HTTP.
76
77 ## Using Content Negotiation In APIs
78
79 As far as I am aware, it was the [Ruby On Rails](https://rubyonrails.org/) community that first went in in a big way
80 using content negotiation to provide both HTML and JSON (and other) formats from the same URL.
81
82 In Rails, this is accomplished via the [
83 `respond_to`](https://apidock.com/rails/ActionController/MimeResponds/respond_to) helper method available in
84 controllers.
85
86 Leaving the gory details of Rails aside, you might have a request like an HTTP `GET` to `/contacts` that ends up
87 invoking
88 a function in a `ContactsController` class that looks like this:
89
90 ```ruby
91 def index
92 @contacts = Contacts.all
93
94 respond_to do |format|
95 format.html # default rendering logic
96 format.json { render json: @contacts }
97 end
98 end
99 ```
100
101 By making use of the `respond_to` helper method, if a client makes a request with the `Accept` header above, the
102 controller
103 will render an HTML response using the Rails templating systems.
104
105 However, if the `Accept` header from the client has the value `application/json` instead, Rails will render the contacts
106 as a JSON array for the client.
107
108 A pretty neat trick: you can keep all your controller logic, like looking up the contacts, the same and just use a
109 bit of ruby/Rails magic to render two different response types using content negotiation. Barely any additional work on
110 top of the normal Model/View/Controller logic.
111
112 You can see why people like the idea!
113
114 ## So What's The Problem?
115
116 So why don't I think this is a good approach to splitting your JSON and HTML APIs up?
117
118 It boils down to the [differences between JSON APIs and Hypermedia (HTML) APIs](/essays/hypermedia-apis-vs-data-apis) I
119 hinted
120 at earlier. In particular:
121
122 * Data APIs should be versioned and should be very stable within a particular version of the API
123 * Data APIs should strive for both regularity and expressiveness due to the arbitrary data needs of consumers
124 * Data APIs typically use some sort of token-based authentication
125 * Data APIs should be rate limited
126 * Hypermedia APIs typically use some sort of session-cookie based authentication
127 * Hypermedia APIs should be driven by the needs of the underlying hypermedia application
128
129 While all of these differences matter and have an effect on your controller code, pulling it in two different
130 directions,
131 it is really the first and last items that make me often choose not to use content negotiation in my applications.
132
133 Your JSON API needs to be a stable set of endpoint that client code can rely on.
134
135 Your hypermedia API, on the other hand, can change dramatically based on the user interface needs of your applications.
136
137 These two things don't mix well.
138
139 To give you a concrete example, consider an end point that renders a detail view of a contact, at, say `/contacts/:id`
140 (where `:id` is a parameter containing the id of the contact to render). Let's say that this page has a "related
141 contacts"
142 section of the UI and, further, computing these related contacts is expensive for some reason.
143
144 In this situation you might choose to use the [Lazy Loading](https://htmx.org/patterns/loading/lazy-load/) pattern to defer
145 loading the related contacts until after the initial contact detail screen has been rendered. This improves perceived
146 performance of the page for your users.
147
148 If you did this, you might put the lazy loaded content at the end-point `/contacts/:id/related`.
149
150 Now, later on, maybe you are able to optimize the computation of related contacts. At this point you might choose to
151 rip the `/contacts/:id/related` end-point out and just render the related contacts information in the initial page
152 render.
153
154 All of this is fine for your hypermedia API: hypermedia, through [the uniform interface & HATEOAS](/essays/hateoas)
155 is _designed_ to handle these sorts of changes.
156
157 However, your JSON API... not so much.
158
159 Your JSON API should remain stable. You can't be adding and removing end-points
160 willy-nilly. Yes, you can have _some_ end-points respond with either JSON or HTML and others only respond with HTML, but
161 it gets messy. What if you accidentally copy-and-paste in the wrong code somewhere, for example.
162
163 Taking all of this into account, as well as things like rate-limiting and so on, I think you can make a strong argument
164 that there should be a [Separation Of Concerns](https://en.wikipedia.org/wiki/Separation_of_concerns) between the JSON
165 API and the hypermedia API.
166
167 (Yes, I am aware of the irony that the person who coined the term [Locality of Behaviour](/essays/locality-of-behaviour)
168 is making a SoC argument.)
169
170 ## So What's The Alternative?
171
172 The alternative is, as I advocate in [Splitting Your APIs](/essays/splitting-your-apis), er, well, splitting your
173 APIs. This means providing different paths (or subdomains, or whatever) for your JSON API and your hypermedia (HTML)
174 API.
175
176 Going back to our contacts API, we might have the following:
177
178 * The JSON API to get all contacts is found at `/api/v1/contacts`
179 * The Hypermedia API to get all contacts is found at `/contacts`
180
181 This layout implies two different controllers and, I say, that's a good thing: the JSON API controller can implement the
182 requirements of a JSON API: rate limiting, stability, maybe an expressive query mechanism like GraphQL.
183
184 Meanwhile, your
185 hypermedia API (really, just your Hypermedia Driven Application endpoints) can change dramatically as your user
186 interface
187 needs change, with highly tuned database queries, end-points to support special UI needs, etc.
188
189 By separating these two concerns, your JSON API can be stable, regular and low-maintenance, and your hypermedia API can
190 be chaotic, specialized and flexible. Each gets its own controller environment to thrive in, without conflicting with
191 one another.
192
193 And this is why I prefer to split my JSON and hypermedia APIs up into separate controllers, rather than use HTTP content
194 negotiation to attempt to reuse controllers for both.