A comprehensive guide to APIs (Application Programming Interfaces) - the protocols and tools for building software applications, covering REST, GraphQL, authentication, and best practices for web development.
An API (Application Programming Interface) is a set of protocols, routines, and tools for building software applications. It specifies how software components should interact and allows different applications to communicate with each other, enabling developers to access functionality and data from external services.
APIs act as intermediaries between different software applications, defining the methods and data formats that applications can use to communicate with each other. They abstract the underlying implementation and provide a standardized way to access functionality.
// Example API request using fetch
const response = await fetch('https://api.rgbmatic.com/colors/ff0000', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-api-key'
}
});
const colorData = await response.json();
console.log(colorData);
// Output: { hex: '#ff0000', rgb: { r: 255, g: 0, b: 0 }, name: 'Red' }REST (Representational State Transfer) is an architectural style for designing networked applications. RESTful APIs follow specific principles:
// RESTful color API endpoints
GET /api/colors // Get all colors
GET /api/colors/ff0000 // Get specific color
POST /api/colors // Create new color
PUT /api/colors/ff0000 // Update color
DELETE /api/colors/ff0000 // Delete color
// Example implementation with Express.js
const express = require('express');
const app = express();
// Get all colors
app.get('/api/colors', async (req, res) => {
try {
const colors = await Color.findAll();
res.json({
success: true,
data: colors,
total: colors.length
});
} catch (error) {
res.status(500).json({
success: false,
error: 'Failed to fetch colors'
});
}
});
// Get specific color
app.get('/api/colors/:hex', async (req, res) => {
try {
const { hex } = req.params;
// Validate hex format
if (!/^[0-9A-Fa-f]{6}$/.test(hex)) {
return res.status(400).json({
success: false,
error: 'Invalid hex color format'
});
}
const color = await Color.findByHex(hex);
if (!color) {
return res.status(404).json({
success: false,
error: 'Color not found'
});
}
res.json({
success: true,
data: color
});
} catch (error) {
res.status(500).json({
success: false,
error: 'Failed to fetch color'
});
}
});
// Create new color
app.post('/api/colors', async (req, res) => {
try {
const { hex, name, tags } = req.body;
// Validation
if (!hex || !name) {
return res.status(400).json({
success: false,
error: 'Hex and name are required'
});
}
const newColor = await Color.create({
hex,
name,
tags: tags || [],
createdAt: new Date()
});
res.status(201).json({
success: true,
data: newColor
});
} catch (error) {
res.status(500).json({
success: false,
error: 'Failed to create color'
});
}
});GraphQL is a query language and runtime for APIs that allows clients to request exactly the data they need:
// GraphQL schema definition
const { gql } = require('apollo-server-express');
const typeDefs = gql`
type Color {
id: ID!
hex: String!
name: String!
rgb: RGB!
hsl: HSL!
tags: [String!]!
createdAt: String!
}
type RGB {
r: Int!
g: Int!
b: Int!
}
type HSL {
h: Int!
s: Int!
l: Int!
}
type Query {
colors(limit: Int, offset: Int): [Color!]!
color(hex: String!): Color
searchColors(query: String!): [Color!]!
}
type Mutation {
createColor(hex: String!, name: String!, tags: [String!]): Color!
updateColor(id: ID!, name: String, tags: [String!]): Color!
deleteColor(id: ID!): Boolean!
}
`;
// GraphQL resolvers
const resolvers = {
Query: {
colors: async (_, { limit = 10, offset = 0 }) => {
return await Color.findAll({ limit, offset });
},
color: async (_, { hex }) => {
return await Color.findByHex(hex);
},
searchColors: async (_, { query }) => {
return await Color.search(query);
}
},
Mutation: {
createColor: async (_, { hex, name, tags }) => {
return await Color.create({ hex, name, tags });
},
updateColor: async (_, { id, name, tags }) => {
return await Color.update(id, { name, tags });
},
deleteColor: async (_, { id }) => {
await Color.delete(id);
return true;
}
},
Color: {
rgb: (color) => {
const { r, g, b } = hexToRgb(color.hex);
return { r, g, b };
},
hsl: (color) => {
const { h, s, l } = hexToHsl(color.hex);
return { h, s, l };
}
}
};
// GraphQL client query
const GET_COLORS = gql`
query GetColors($limit: Int) {
colors(limit: $limit) {
id
hex
name
rgb {
r
g
b
}
tags
}
}
`;
// Usage with Apollo Client
const { data, loading, error } = useQuery(GET_COLORS, {
variables: { limit: 20 }
});// JWT Authentication middleware
const jwt = require('jsonwebtoken');
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({
success: false,
error: 'Access token required'
});
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({
success: false,
error: 'Invalid or expired token'
});
}
req.user = user;
next();
});
};
// API Key authentication
const authenticateApiKey = async (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey) {
return res.status(401).json({
success: false,
error: 'API key required'
});
}
try {
const keyData = await ApiKey.findByKey(apiKey);
if (!keyData || !keyData.active) {
return res.status(401).json({
success: false,
error: 'Invalid API key'
});
}
// Rate limiting check
const usage = await checkRateLimit(apiKey);
if (usage.exceeded) {
return res.status(429).json({
success: false,
error: 'Rate limit exceeded',
resetTime: usage.resetTime
});
}
req.apiKey = keyData;
next();
} catch (error) {
res.status(500).json({
success: false,
error: 'Authentication failed'
});
}
};
// OAuth 2.0 implementation
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
}, async (accessToken, refreshToken, profile, done) => {
try {
let user = await User.findByGoogleId(profile.id);
if (!user) {
user = await User.create({
googleId: profile.id,
email: profile.emails[0].value,
name: profile.displayName,
avatar: profile.photos[0].value
});
}
return done(null, user);
} catch (error) {
return done(error, null);
}
}));// Redis-based rate limiting
const redis = require('redis');
const client = redis.createClient();
class RateLimiter {
constructor(options = {}) {
this.windowMs = options.windowMs || 15 * 60 * 1000; // 15 minutes
this.maxRequests = options.maxRequests || 100;
this.keyGenerator = options.keyGenerator || ((req) => req.ip);
}
async checkLimit(req) {
const key = `rate_limit:${this.keyGenerator(req)}`;
const current = await client.get(key);
if (current === null) {
await client.setex(key, Math.ceil(this.windowMs / 1000), 1);
return {
allowed: true,
remaining: this.maxRequests - 1,
resetTime: Date.now() + this.windowMs
};
}
const count = parseInt(current);
if (count >= this.maxRequests) {
const ttl = await client.ttl(key);
return {
allowed: false,
remaining: 0,
resetTime: Date.now() + (ttl * 1000)
};
}
await client.incr(key);
return {
allowed: true,
remaining: this.maxRequests - count - 1,
resetTime: Date.now() + this.windowMs
};
}
middleware() {
return async (req, res, next) => {
try {
const result = await this.checkLimit(req);
res.set({
'X-RateLimit-Limit': this.maxRequests,
'X-RateLimit-Remaining': result.remaining,
'X-RateLimit-Reset': new Date(result.resetTime).toISOString()
});
if (!result.allowed) {
return res.status(429).json({
success: false,
error: 'Too many requests',
retryAfter: Math.ceil((result.resetTime - Date.now()) / 1000)
});
}
next();
} catch (error) {
console.error('Rate limiting error:', error);
next(); // Allow request on rate limiter failure
}
};
}
}
// Usage
const rateLimiter = new RateLimiter({
windowMs: 15 * 60 * 1000, // 15 minutes
maxRequests: 100,
keyGenerator: (req) => req.apiKey?.id || req.ip
});
app.use('/api', rateLimiter.middleware());// OpenAPI specification
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'RGBmatic Color API',
version: '1.0.0',
description: 'API for color conversion and management',
contact: {
name: 'API Support',
email: 'support@rgbmatic.com'
}
},
servers: [
{
url: 'https://api.rgbmatic.com/v1',
description: 'Production server'
},
{
url: 'https://staging-api.rgbmatic.com/v1',
description: 'Staging server'
}
],
components: {
securitySchemes: {
ApiKeyAuth: {
type: 'apiKey',
in: 'header',
name: 'X-API-Key'
},
BearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT'
}
},
schemas: {
Color: {
type: 'object',
required: ['hex', 'name'],
properties: {
id: {
type: 'string',
description: 'Unique color identifier'
},
hex: {
type: 'string',
pattern: '^#[0-9A-Fa-f]{6}$',
description: 'Hexadecimal color value'
},
name: {
type: 'string',
description: 'Color name'
},
rgb: {
$ref: '#/components/schemas/RGB'
},
hsl: {
$ref: '#/components/schemas/HSL'
},
tags: {
type: 'array',
items: {
type: 'string'
}
}
}
},
RGB: {
type: 'object',
properties: {
r: { type: 'integer', minimum: 0, maximum: 255 },
g: { type: 'integer', minimum: 0, maximum: 255 },
b: { type: 'integer', minimum: 0, maximum: 255 }
}
},
HSL: {
type: 'object',
properties: {
h: { type: 'integer', minimum: 0, maximum: 360 },
s: { type: 'integer', minimum: 0, maximum: 100 },
l: { type: 'integer', minimum: 0, maximum: 100 }
}
}
}
}
},
apis: ['./routes/*.js']
};
const specs = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
/**
* @swagger
* /colors:
* get:
* summary: Get all colors
* tags: [Colors]
* parameters:
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* maximum: 100
* default: 10
* description: Number of colors to return
* - in: query
* name: offset
* schema:
* type: integer
* minimum: 0
* default: 0
* description: Number of colors to skip
* responses:
* 200:
* description: List of colors
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* data:
* type: array
* items:
* $ref: '#/components/schemas/Color'
* total:
* type: integer
* 500:
* description: Server error
*/// Jest API testing
const request = require('supertest');
const app = require('../app');
describe('Color API', () => {
describe('GET /api/colors', () => {
test('should return list of colors', async () => {
const response = await request(app)
.get('/api/colors')
.expect(200);
expect(response.body.success).toBe(true);
expect(Array.isArray(response.body.data)).toBe(true);
expect(typeof response.body.total).toBe('number');
});
test('should respect limit parameter', async () => {
const response = await request(app)
.get('/api/colors?limit=5')
.expect(200);
expect(response.body.data.length).toBeLessThanOrEqual(5);
});
});
describe('GET /api/colors/:hex', () => {
test('should return specific color', async () => {
const response = await request(app)
.get('/api/colors/ff0000')
.expect(200);
expect(response.body.success).toBe(true);
expect(response.body.data.hex).toBe('#ff0000');
});
test('should return 404 for non-existent color', async () => {
const response = await request(app)
.get('/api/colors/999999')
.expect(404);
expect(response.body.success).toBe(false);
expect(response.body.error).toBe('Color not found');
});
test('should return 400 for invalid hex format', async () => {
const response = await request(app)
.get('/api/colors/invalid')
.expect(400);
expect(response.body.success).toBe(false);
expect(response.body.error).toBe('Invalid hex color format');
});
});
describe('POST /api/colors', () => {
test('should create new color', async () => {
const newColor = {
hex: '#00ff00',
name: 'Green',
tags: ['primary', 'bright']
};
const response = await request(app)
.post('/api/colors')
.send(newColor)
.expect(201);
expect(response.body.success).toBe(true);
expect(response.body.data.hex).toBe('#00ff00');
expect(response.body.data.name).toBe('Green');
});
test('should return 400 for missing required fields', async () => {
const response = await request(app)
.post('/api/colors')
.send({ hex: '#0000ff' })
.expect(400);
expect(response.body.success).toBe(false);
expect(response.body.error).toBe('Hex and name are required');
});
});
});Explore these comprehensive pillar articles related to API
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to triadic color schemes - three colors evenly spaced around the color wheel that create balanced, vibrant, and dynamic visual compositions with mathematical precision and artistic appeal.
Discover more about API and related color theory concepts
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary