api

ruby
module CursorPagination
  extend ActiveSupport::Concern

  private

  def paginate_with_cursor(scope, per_page: 20)

Pagination with cursor-based approach

rails api pagination
by Alex Kumar 1 tab
ruby
class Article < ApplicationRecord
  scope :ranked, -> { order(score: :desc, id: :desc) }

  scope :after_cursor, ->(cursor) do
    return all if cursor.nil?

Deterministic Sorting with Secondary Key

rails activerecord pagination
by codesnips 4 tabs
ruby
module KeysetPageable
  extend ActiveSupport::Concern

  included do
    scope :keyset_page, ->(cursor: nil, per: 20) do
      per = per.to_i.clamp(1, 100)

Safe Pagination with Keyset (No OFFSET)

rails activerecord performance
by codesnips 3 tabs
ruby
class Contract
  INVALID = Object.new.freeze

  COERCERS = {
    string: ->(v) { v.is_a?(String) ? v : v.to_s },
    integer: ->(v) { Integer(v.to_s) rescue INVALID },

Validated JSON Schema with dry-validation-style contract (lightweight)

api validation contracts
by codesnips 4 tabs
ruby
class CreateApiKeys < ActiveRecord::Migration[6.1]
  def change
    create_table :api_keys do |t|
      t.references :user, null: false, foreign_key: true
      t.string :name, null: false
      t.string :key_digest, null: false

API key authentication for service-to-service calls

rails authentication api
by Alex Kumar 3 tabs
ruby
class RateLimiter
  def initialize(key:, limit:, window:)
    @key = "rate_limit:#{key}"
    @limit = limit
    @window = window
  end

API throttling with custom Redis-based limiter

rails redis rate-limiting
by Alex Kumar 2 tabs
typescript
import { Injectable } from '@nestjs/common';

export interface RateLimitResult {
  allowed: boolean;
  remaining: number;
  limit: number;

Sliding-Window Webhook Rate Limiting with a NestJS Interceptor and In-Memory Counter

typescript nestjs rate-limiting
by codesnips 3 tabs
typescript
export class AppError extends Error {
  public readonly statusCode: number;
  public readonly code: string;
  public readonly isOperational: boolean;

  constructor(message: string, statusCode = 500, code = 'INTERNAL_ERROR', isOperational = true) {

Backend: normalize errors with a single Express handler

express error-handling typescript
by codesnips 4 tabs
typescript
export interface Post {
  id: string;
  title: string;
  updatedAt: string;
}

Deduplicating Paginated API Results With a Normalized Entity Store and Reducer

react reducer normalization
by codesnips 3 tabs
go
package api

import (
  "encoding/json"
  "net/http"
)

WriteJSON helper with consistent headers and status

go http json
by Leah Thompson 1 tab
python
import re


class APIVersionMiddleware:
    """Extract API version from request and add to request object."""

Django middleware for API versioning

django python api
by Priya Sharma 1 tab
php
<?php

namespace App\Domain;

use InvalidArgumentException;

Serializing a Money Value Object with a Custom Symfony Normalizer

symfony serializer value-object
by codesnips 3 tabs