Claude vs DeepSeek vs Grok: JSON
JSON API Tutorial - Simple Guide
What is JSON API?
JSON API is a specification for building APIs in JSON format. It standardizes how to structure JSON responses, making APIs more consistent and easier to work with.
Basic JSON API Structure
Single Resource Response
{
"data": {
"type": "users",
"id": "1",
"attributes": {
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
}
}
Multiple Resources Response
{
"data": [
{
"type": "users",
"id": "1",
"attributes": {
"name": "John Doe",
"email": "john@example.com"
}
},
{
"type": "users",
"id": "2",
"attributes": {
"name": "Jane Smith",
"email": "jane@example.com"
}
}
]
}
Key Components
1. data (required)
Contains the primary data for the response.
2. type (required)
Identifies the resource type (e.g., "users", "posts", "comments").
3. id (required for existing resources)
Unique identifier for the resource.
4. attributes
Contains the resource's data (excluding id and relationships).
Common HTTP Methods
GET - Retrieve Resources
# Get all users
GET /api/users# Get specific user
GET /api/users/1
POST - Create Resource
POST /api/users
Content-Type: application/json{
"data": {
"type": "users",
"attributes": {
"name": "New User",
"email": "new@example.com"
}
}
}
PATCH - Update Resource
PATCH /api/users/1
Content-Type: application/json{
"data": {
"type": "users",
"id": "1",
"attributes": {
"name": "Updated Name"
}
}
}
DELETE - Remove Resource
DELETE /api/users/1
Error Handling
{
"errors": [
{
"status": "400",
"title": "Validation Error",
"detail": "Email is required",
"source": {
"pointer": "/data/attributes/email"
}
}
]
}
Simple JavaScript Examples
Fetching Data
// Get all users
fetch('/api/users', {
headers: {
'Accept': 'application/vnd.api+json'
}
})
.then(response => response.json())
.then(data => {
console.log(data.data); // Array of users
});
Creating Data
// Create new user
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/vnd.api+json',
'Accept': 'application/vnd.api+json'
},
body: JSON.stringify({
data: {
type: 'users',
attributes: {
name: 'John Doe',
email: 'john@example.com'
}
}
})
})
.then(response => response.json())
.then(data => {
console.log('Created user:', data.data);
});
Content Type Header
Always use the official JSON API content type:
Content-Type: application/vnd.api+json
Accept: application/vnd.api+json
Benefits of JSON API
- Standardized - Consistent structure across all endpoints
- Self-documenting - Clear resource types and relationships
- Efficient - Built-in support for sparse fieldsets and includes
- Predictable - Same patterns for all CRUD operations
Quick Tips
- Always include
type
andid
for
I'll create a simple JSON API tutorial for you. Here's a complete example using Node.js and Express:
1. Setup Project
First, create a new project and install dependencies:
mkdir simple-json-api
cd simple-json-api
npm init -y
npm install express
2. Basic Server Setup
Create server.js
:
const express = require('express');
const app = express();
const PORT = 3000;// Middleware to parse JSON requests
app.use(express.json());
// Sample data
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },
{ id: 3, name: 'Bob Johnson', email: 'bob@example.com' }
];
let posts = [
{ id: 1, title: 'First Post', content: 'This is the first post', userId: 1 },
{ id: 2, title: 'Second Post', content: 'This is the second post', userId: 2 }
];
// Routes
app.get('/', (req, res) => {
res.json({
message: 'Welcome to Simple JSON API',
endpoints: [
'GET /users - Get all users',
'GET /users/:id - Get user by ID',
'POST /users - Create new user',
'GET /posts - Get all posts',
'GET /posts/:id - Get post by ID'
]
});
});
// GET all users
app.get('/users', (req, res) => {
res.json({
success: true,
data: users,
count: users.length
});
});
// GET user by ID
app.get('/users/:id', (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).json({
success: false,
message: 'User not found'
});
}
res.json({
success: true,
data: user
});
});
// POST create new user
app.post('/users', (req, res) => {
const { name, email } = req.body;
// Simple validation
if (!name || !email) {
return res.status(400).json({
success: false,
message: 'Name and email are required'
});
}
const newUser = {
id: users.length + 1,
name,
email
};
users.push(newUser);
res.status(201).json({
success: true,
message: 'User created successfully',
data: newUser
});
});
// GET all posts
app.get('/posts', (req, res) => {
// Join posts with user data
const postsWithUsers = posts.map(post => {
const user = users.find(u => u.id === post.userId);
return {
...post,
author: user ? user.name : 'Unknown'
};
});
res.json({
success: true,
data: postsWithUsers
});
});
// GET post by ID
app.get('/posts/:id', (req, res) => {
const id = parseInt(req.params.id);
const post = posts.find(p => p.id === id);
if (!post) {
return res.status(404).json({
success: false,
message: 'Post not found'
});
}
// Add author information
const user = users.find(u => u.id === post.userId);
const postWithAuthor = {
...post,
author: user ? user.name : 'Unknown'
};
res.json({
success: true,
data: postWithAuthor
});
});
// Error handling middleware
app.use((req, res) => {
res.status(404).json({
success: false,
message: 'Endpoint not found'
});
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
3. Testing the API
Run the server:
node server.js
Test with curl commands:
Get all users:
curl http://localhost:3000/users
Get user by ID:
curl http://localhost:3000/users/1
Create new user:
curl -X POST http://localhost:3000/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice Brown","email":"alice@example.com"}'
Get all posts:
curl http://localhost:3000/posts
4. Enhanced Version with Better Structure
For a more organized approach, create separate route files:
routes/users.js:
const express = require('express');
const router = express.Router();let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
// GET all users
router.get('/', (req, res) => {
res.json(users);
});
// GET user by ID
router.get('/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// POST create user
router.post('/', (req, res) => {
const newUser = {
id: users.length + 1,
...req.body
};
users.push(newUser);
res.status(201).json(newUser);
});
module.exports = router;
Updated server.js:
const express = require('express');
const app = express();app.use(express.json());
// Import routes
const userRoutes = require('./routes/users');
// Use routes
app.use('/users', userRoutes);
app.get('/', (req, res) => {
res.json({ message: 'API is working!' });
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Key JSON API Concepts:
- HTTP Methods: GET (read), POST (create), PUT/PATCH (update), DELETE (remove)
- Status Codes: 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found)
- Response Format: Always return JSON with consistent structure
- Error Handling: Provide meaningful error messages
- Validation: Check incoming data before processing
This gives you a solid foundation for building JSON APIs! You can extend it by adding database integration, authentication, and more endpoints.
Let's create a simple JSON API tutorial using Node.js and Express. This tutorial will guide you through building a basic RESTful API that handles JSON data with endpoints for creating, reading, updating, and deleting data.
What You'll Learn
- Setting up a Node.js project with Express.
- Creating a simple JSON API with basic CRUD operations (Create, Read, Update, Delete).
- Testing the API using tools like Postman or cURL.
Prerequisites
- Node.js and npm installed on your machine.
- Basic understanding of JavaScript.
- A code editor (e.g., VS Code).
Step 1: Set Up the Project
- Create a new directory for your project and navigate to it:
mkdir json-api-tutorial
cd json-api-tutorial
- Initialize a new Node.js project:
npm init -y
- Install the required dependencies (Express in this case):
npm install express
Step 2: Create the Server
Create a file named
server.js
and add the following code to set up a basic Express server:const express = require('express');
const app = express();
const PORT = 3000;// Middleware to parse JSON bodies
app.use(express.json());
// Sample in-memory data (acting as a database)
let users = [
{ id: 1, name: "John Doe", email: "john@example.com" },
{ id: 2, name: "Jane Smith", email: "jane@example.com" }
];
// API Endpoints
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET a single user by ID
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
});
// POST a new user
app.post('/api/users', (req, res) => {
const user = {
id: users.length + 1,
name: req.body.name,
email: req.body.email
};
users.push(user);
res.status(201).json(user);
});
// PUT (update) a user by ID
app.put('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: "User not found" });
user.name = req.body.name;
user.email = req.body.email;
res.json(user);
});
// DELETE a user by ID
app.delete('/api/users/:id', (req, res) => {
const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
if (userIndex === -1) return res.status(404).json({ message: "User not found" });
users.splice(userIndex, 1);
res.status(204).send(); // No content
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Step 3: Run the Server
Run the server using the following command:
node server.js
You should see the message: Server running on http://localhost:3000
.
Step 4: Test the API
You can test the API using tools like Postman, cURL, or even a browser for GET requests. Below are examples of how to interact with the API using cURL or Postman.
1. GET all users
URL:
http://localhost:3000/api/users
- cURL Command:
curl http://localhost:3000/api/users
- Expected Response:
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Smith", "email": "jane@example.com" }
]
2. GET a single user
URL:
http://localhost:3000/api/users/1
- cURL Command:
curl http://localhost:3000/api/users/1
- Expected Response:
{ "id": 1, "name": "John Doe", "email": "john@example.com" }
3. POST a new user
URL:
http://localhost:3000/api/users
- cURL Command:
curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d '{"name": "Alice Brown", "email": "alice@example.com"}'
- Expected Response:
{ "id": 3, "name": "Alice Brown", "email": "alice@example.com" }
4. PUT (update) a user
URL:
http://localhost:3000/api/users/1
- cURL Command:
curl -X PUT http://localhost:3000/api/users/1 -H "Content-Type: application/json" -d '{"name": "John Updated", "email": "john.updated@example.com"}'
- Expected Response:
{ "id": 1, "name": "John Updated", "email": "john.updated@example.com" }
5. DELETE a user
URL:
http://localhost:3000/api/users/1
- cURL Command:
curl -X DELETE http://localhost:3000/api/users/1
- Expected Response: (No content, status code 204)
Step 5: Notes and Improvements
- Data Persistence: This example uses an in-memory array as a database. In a real application, you should use a database like MongoDB, PostgreSQL, or MySQL.
- Error Handling: Add better error handling for invalid input data.
- Validation: Use libraries like
Joi
orexpress-validator
to validate request data. - Security: Add authentication and authorization for protected routes.
Conclusion
You’ve just built a simple JSON API with Node.js and Express! You can now expand this API by adding more features, connecting it to a real database, or securing it with authentication. Let me know if you want to dive deeper into any of these topics!
💡 Try this comparison yourself:Compare AI models side-by-side on SNEOS
Analysis
This comparison demonstrates the different approaches each AI model takes when responding to the same prompt. Here are the key differences observed:
Response Characteristics
Claude: Provides a direct response with 38 sentences.
DeepSeek: Provides a concise response with 113 sentences.
Grok: Provides a direct response with 96 sentences.
Key Takeaways
- Each model brings unique strengths to this type of query
- Response styles vary significantly between models
- Consider your specific use case when choosing between these models
Try This Comparison Yourself
Want to test these models with your own prompts? Visit SNEOS.com to compare AI responses side-by-side in real-time.
This comparison was generated using the SNEOS AI Comparison ToolPublished: October 01, 2025 | Models: Claude, DeepSeek, Grok