Skip to content

Instantly share code, notes, and snippets.

@partkyle
Last active December 22, 2015 08:08
Show Gist options
  • Select an option

  • Save partkyle/6442389 to your computer and use it in GitHub Desktop.

Select an option

Save partkyle/6442389 to your computer and use it in GitHub Desktop.
XML & JSON

Problems with both XML and JSON as api responses

Say we have a simple api endpoint:

GET /profile
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json

{
    "username": "partkyle",
	"email": "[email protected]"
}

And the comparable xml endpoint:

GET /profile
Accept: text/xml
HTTP/1.1 200 OK
Content-Type: application/xml

<?xml version="1.0" encoding="UTF-8" ?>
<profile>
	<username>partkyle</username>
	<email>[email protected]</email>
</profile>

The main problem here is, where did the word "profile" come from in the xml version? The response in the json is different because it does not require a root node.

We could write our json responses in a way that is more compatible to infer these decisions automatically:

HTTP/1.1 200 OK
Content-Type: application/json

{
	"profile": {
		"username": "partkyle",
		"email": "[email protected]"
	}
}

I feel this clutters the api.

Another problem is expressed when using arrays of elements:

GET /unsubscribes
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json

{
	"unsubscribes": [
		{"email": "[email protected]", "created_at": "2012-01-01"},
		{"email": "[email protected]", "created_at": "2012-01-01"},
		{"email": "[email protected]", "created_at": "2012-01-01"}
	]
}

and the xml counterpart:

GET /unsubscribes
Accept: text/xml
HTTP/1.1 200 OK
Content-Type: text/xml

<?xml version="1.0" encoding="UTF-8" ?>
<unsubscribes>
	<unsubscribe>
		<email>[email protected]</email>
		<created_at>2012-01-01</created_at>
	</unsubscribe>
	<unsubscribe>
		<email>[email protected]</email>
		<created_at>2012-01-01</created_at>
	</unsubscribe>
	<unsubscribe>
		<email>[email protected]</email>
		<created_at>2012-01-01</created_at>
	</unsubscribe>
</unsubscribes>

Where did the "unsubscribe" text come from? It's the singular version of the word "unsubscribes."

I don't feel it would be a good use of time and effort to handle the pluralization of these names. I suppose we could use something generic instead, but I just feel there is extra complexity here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment