📄 JSON:API = Standardized APIs
Consistency matters. JSON:API specification creates standardized REST APIs.
📝 JSON:API Response Format
// Success Response
{
"data": {
"type": "users",
"id": "123",
"attributes": {
"name": "John Doe",
"email": "john@example.com"
},
"relationships": {
"posts": {
"data": [
{ "type": "posts", "id": "1" },
{ "type": "posts", "id": "2" }
]
}
}
},
"included": [
{
"type": "posts",
"id": "1",
"attributes": {
"title": "Post 1",
"content": "Content..."
}
}
],
"links": {
"self": "/api/users/123"
}
}
// Error Response
{
"errors": [
{
"status": "404",
"code": "USER_NOT_FOUND",
"title": "User Not Found",
"detail": "User with ID 123 not found"
}
]
}
🎯 Implementation
// .NET Core with JSON:API
public class UserController : ControllerBase
{
[HttpGet("api/users/{id}")]
public IActionResult GetUser(int id)
{
var user = _context.Users.Find(id);
if (user == null)
{
return NotFound(new
{
errors = new[]
{
new
{
status = "404",
code = "USER_NOT_FOUND",
title = "User Not Found"
}
}
});
}
return Ok(new
{
data = new
{
type = "users",
id = user.Id.ToString(),
attributes = new
{
name = user.Name,
email = user.Email
}
}
});
}
}
// JavaScript Client
class JsonApiClient {
async get(type, id) {
const response = await fetch(`/api/${type}/${id}`);
const json = await response.json();
if (json.errors) {
throw new Error(json.errors[0].title);
}
return json.data;
}
}
💡 JSON:API Tips
- Use consistent resource types
- Include relationships
- Use proper error format
- Add pagination links
- Include sparse fieldsets
JSON:API brings consistency to REST APIs. It makes APIs predictable and easy to consume.
