JSON in REST APIs

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate.

JSON Syntax

{
  "string": "value",
  "number": 123,
  "boolean": true,
  "null": null,
  "array": [1, 2, 3],
  "object": {
    "nested": "value"
  }
}

JSON in REST APIs

// Node.js/Express - Sending JSON
app.get('/api/users/:id', async (req, res) => {
  const user = await User.findById(req.params.id);
  res.json(user); // Automatically sets Content-Type: application/json
});

// Receiving JSON
app.use(express.json()); // Parse JSON request bodies

app.post('/api/users', async (req, res) => {
  const { name, email } = req.body;
  const user = await User.create({ name, email });
  res.status(201).json(user);
});
// .NET - JSON serialization/deserialization
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUser(int id)
{
    var user = await _context.Users.FindAsync(id);
    return Ok(user); // Automatically serialized to JSON
}

[HttpPost]
public async Task<ActionResult<User>> CreateUser(CreateUserDto dto)
{
    // dto automatically deserialized from JSON
    var user = new User { Name = dto.Name, Email = dto.Email };
    _context.Users.Add(user);
    await _context.SaveChangesAsync();
    
    return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
}
// Angular - Working with JSON
@Injectable()
export class UserService {
  getUser(id: string): Observable<User> {
    // HttpClient automatically parses JSON response
    return this.http.get<User>(`${this.apiUrl}/users/${id}`);
  }
  
  createUser(user: CreateUserDto): Observable<User> {
    // HttpClient automatically stringifies object to JSON
    return this.http.post<User>(`${this.apiUrl}/users`, user);
  }
}

JSON Response Structures

Single Resource

{
  "id": "123",
  "name": "John Doe",
  "email": "john@example.com",
  "role": "admin",
  "createdAt": "2024-01-01T00:00:00Z"
}

Collection Resource

{
  "data": [
    {
      "id": "123",
      "name": "John Doe",
      "email": "john@example.com"
    },
    {
      "id": "124",
      "name": "Jane Smith",
      "email": "jane@example.com"
    }
  ],
  "total": 2,
  "page": 1,
  "pageSize": 10
}

Error Response

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      {
        "field": "email",
        "message": "Email is required"
      },
      {
        "field": "name",
        "message": "Name must be at least 2 characters"
      }
    ]
  }
}

JSON Naming Conventions

{
  "camelCase": "JavaScript/TypeScript standard",
  "snake_case": "Python/Ruby standard",
  "PascalCase": "C# standard",
  "kebab-case": "Rarely used in JSON"
}
// Node.js - camelCase (recommended for JavaScript)
{
  "userId": "123",
  "firstName": "John",
  "lastName": "Doe",
  "createdAt": "2024-01-01T00:00:00Z"
}
// .NET - Configure JSON naming
services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = 
            JsonNamingPolicy.CamelCase;
    });

Nested Objects

{
  "id": "123",
  "name": "John Doe",
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "country": "USA"
  },
  "orders": [
    {
      "id": "789",
      "total": 99.99,
      "items": [
        {
          "productId": "456",
          "quantity": 2,
          "price": 49.99
        }
      ]
    }
  ]
}

JSON Arrays

{
  "users": [
    { "id": "1", "name": "John" },
    { "id": "2", "name": "Jane" }
  ],
  "tags": ["javascript", "rest", "api"],
  "numbers": [1, 2, 3, 4, 5]
}

JSON Serialization

// Node.js - Custom serialization
class User {
  constructor(id, name, email, password) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.password = password; // Sensitive
  }
  
  toJSON() {
    return {
      id: this.id,
      name: this.name,
      email: this.email
      // password excluded
    };
  }
}

const user = new User('123', 'John', 'john@example.com', 'secret');
res.json(user); // Password not included
// .NET - Custom serialization
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    
    [JsonIgnore] // Exclude from JSON
    public string Password { get; set; }
}

JSON Parsing

// Node.js - Parse JSON string
const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);

// Stringify object
const user = { name: 'John', age: 30 };
const json = JSON.stringify(user);

// Pretty print
const prettyJson = JSON.stringify(user, null, 2);

JSON Content Type

// Set correct Content-Type header
app.get('/api/users', (req, res) => {
  res.set('Content-Type', 'application/json');
  res.send(JSON.stringify({ users: [] }));
});

// Or use res.json() which sets it automatically
app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});

JSON Schema Validation

const Ajv = require('ajv');
const ajv = new Ajv();

const userSchema = {
  type: 'object',
  properties: {
    name: { type: 'string', minLength: 2 },
    email: { type: 'string', format: 'email' },
    age: { type: 'number', minimum: 0 }
  },
  required: ['name', 'email']
};

const validate = ajv.compile(userSchema);

app.post('/api/users', (req, res) => {
  const valid = validate(req.body);
  if (!valid) {
    return res.status(400).json({ errors: validate.errors });
  }
  // Process valid data
});

Interview Tips

  • Explain JSON: Lightweight data format
  • Show syntax: Objects, arrays, primitives
  • Demonstrate usage: Node.js, .NET, Angular
  • Discuss naming: camelCase convention
  • Mention serialization: Exclude sensitive fields
  • Show validation: Schema validation

Summary

JSON is the standard data format for REST APIs. Lightweight, human-readable, and language-independent. Use camelCase for JavaScript/TypeScript. Structure responses consistently with data, metadata, and errors. Exclude sensitive fields during serialization. Validate JSON against schemas. Essential for modern REST API development.

Test Your Knowledge

Take a quick quiz to test your understanding of this topic.

Test Your Restful-api Knowledge

Ready to put your skills to the test? Take our interactive Restful-api quiz and get instant feedback on your answers.