← Back to Blog

JSON APIs and REST Services: Complete Development Guide

Learn to build and consume JSON-based REST APIs. Covers HTTP methods, authentication, best practices, and real-world implementation examples.

Big JSON Team15 min readadvanced
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

15 min read

REST API Fundamentals

REST (Representational State Transfer) APIs use JSON as the primary data format for request and response bodies.

HTTP Methods

  • GET: Retrieve data
  • POST: Create new resource
  • PUT: Update entire resource
  • PATCH: Partial update
  • DELETE: Remove resource

Building APIs with Express.js

import express from 'express';

const app = express();

app.use(express.json());

let users = [

{ id: 1, name: 'Alice' },

{ id: 2, name: 'Bob' }

];

// GET all users

app.get('/api/users', (req, res) => {

res.json(users);

});

// GET single user

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({ error: 'Not found' });

res.json(user);

});

// POST create user

app.post('/api/users', (req, res) => {

const user = { id: users.length + 1, ...req.body };

users.push(user);

res.status(201).json(user);

});

app.listen(3000);

Building APIs with Python FastAPI

from fastapi import FastAPI, HTTPException

from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):

name: str

email: str

users_db = []

@app.get("/api/users")

def get_users():

return users_db

@app.post("/api/users", status_code=201)

def create_user(user: User):

users_db.append(user.dict())

return user

@app.get("/api/users/{user_id}")

def get_user(user_id: int):

if user_id >= len(users_db):

raise HTTPException(status_code=404, detail="Not found")

return users_db[user_id]

Consuming APIs

JavaScript Fetch

// GET request

const response = await fetch('https://api.example.com/users');

const users = await response.json();

// POST request

const newUser = await fetch('https://api.example.com/users', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })

});

Python Requests

import requests

# GET

response = requests.get('https://api.example.com/users')

users = response.json()

# POST

new_user = requests.post(

'https://api.example.com/users',

json={'name': 'Alice', 'email': 'alice@example.com'}

)

API Response Patterns

Success Response

{

"success": true,

"data": {

"id": 1,

"name": "Alice"

}

}

Error Response

{

"success": false,

"error": {

"code": "VALIDATION_ERROR",

"message": "Invalid input",

"details": [

{

"field": "email",

"message": "Invalid email format"

}

]

}

}

Authentication

Bearer Token

fetch('/api/protected', {

headers: {

'Authorization': 'Bearer your-token-here'

}

});

API Key

fetch('/api/data', {

headers: {

'X-API-Key': 'your-api-key'

}

});

Pagination

{

"data": [...],

"pagination": {

"page": 1,

"perPage": 20,

"total": 156,

"totalPages": 8

}

}

Best Practices

  • Use appropriate HTTP status codes
  • Version your API (/api/v1/users)
  • Implement rate limiting
  • Validate all input data
  • Use HTTPS in production
  • Document your API (OpenAPI/Swagger)
  • Status Codes

    • 200: OK
    • 201: Created
    • 204: No Content
    • 400: Bad Request
    • 401: Unauthorized
    • 404: Not Found
    • 500: Internal Server Error

    Conclusion

    REST APIs with JSON are the backbone of modern web applications. Master HTTP methods, proper status codes, and authentication for building robust APIs!

    Share:

    Related Articles

    Read in other languages