Implement content negotiation for supporting multiple response formats (JSON, XML, CSV, etc.).
You are a standards-focused API architect implementing proper HTTP content negotiation.
## CONTEXT
I need to support multiple response formats in my API.
**Requirements:**
- Formats Needed: {{FORMATS}}
- Client Types: {{CLIENTS}}
- Default Format: {{DEFAULT}}
- Legacy Support: {{LEGACY}}
## TASK
Design content negotiation:
### 1. ACCEPT HEADER
```
GET /api/users
Accept: application/json
GET /api/users
Accept: text/csv
GET /api/users
Accept: application/xml
```
### 2. QUALITY VALUES
```
Accept: application/json;q=1.0, application/xml;q=0.8, */*;q=0.1
```
### 3. FORMAT EXTENSION (Alternative)
```
GET /api/users.json
GET /api/users.csv
GET /api/users.xml
```
### 4. RESPONSE HEADERS
```
Content-Type: application/json; charset=utf-8
Vary: Accept
```
### 5. IMPLEMENTATION
```typescript
const formatters = {
'application/json': (data) => JSON.stringify(data),
'text/csv': (data) => convertToCsv(data),
'application/xml': (data) => convertToXml(data),
};
function negotiate(req, data) {
const accept = req.headers.accept;
const format = selectFormat(accept, Object.keys(formatters));
return {
contentType: format,
body: formatters[format](data)
};
}
```
### 6. 406 NOT ACCEPTABLE
```json
{
"error": "Not Acceptable",
"message": "Supported formats: application/json, text/csv",
"supportedTypes": ["application/json", "text/csv"]
}
```Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[{FORMATS][{CLIENTS][{DEFAULT][{LEGACY]{
'application/json': (data) => JSON.stringify(data),
'text/csv': (data) => convertToCsv(data),
'application/xml': (data) => convertToXml(data),
}{
const accept = req.headers.accept;
const format = selectFormat(accept, Object.keys(formatters));
return {
contentType: format,
body: formatters[format](data)
}{
"error": "Not Acceptable",
"message": "Supported formats: application/json, text/csv",
"supportedTypes": ["application/json", "text/csv"]
}