GPT 5 Available DeepSeek V4 Available Kimi K2.6 Available GPT 5 Mini Available DeepSeek V3.2 Available GPT 5.4 Available GPT 5.4 mini Available Grok 4 Available Llama 3.1 Available Phi 4 Available GLM 5.2 by Z.ai Available Claude Haiku 5.5 Available
Free AI chat models, no sign upSee all chat models →
Buy me a coffee
GPT 5 Available DeepSeek V4 Available Kimi K2.6 Available GPT 5 Mini Available DeepSeek V3.2 Available GPT 5.4 Available GPT 5.4 mini Available Grok 4 Available Llama 3.1 Available Phi 4 Available GLM 5.2 by Z.ai Available Claude Haiku 5.5 Available
Free AI chat models, no sign upSee all chat models →
Free REST API Code

API Generator

Create REST API endpoints for free with AIFreeForever's API Generator, in Express.js, FastAPI, Spring Boot and four other frameworks. Each endpoint comes with validation, error handling and a comment that documents it.

Pick the framework and language to generate your API codePick the framework and language
Framework
Programming Language
Describe your endpoint
Quick frameworks you can choose from

What is API Generator

This tool generates professional REST API endpoints complete with request validation, error handling, and proper HTTP methods. Get production-ready API code with best practices built in.

Centered hero graphic for Ai Api Generator showing a refined AI API generator UI panel with an API prompt field, dropdown, toggle, and Generate button over a developer workflow background with subtle grid lines and premium tool aesthetics.
API GeneratorMade by AIFreeForever
Generate my API code free
DetailInformation
ToolAPI Generator by AIFreeForever
What it can doWrite REST API endpoints with validation, status codes and error handling
FrameworksExpress.js, FastAPI, Django REST and more
LanguagesNode.js, Python, Java and more
OutputDocumented API code to copy or download as a file of the language
PricingFree

Why Use the API Generator?

Describe an endpoint and the API Generator writes the routes, input validation, status codes and error handling for the framework you pick. Each endpoint also comes with a comment that documents it. Secrets are read from environment variables, so the code is ready to test on your own server. It runs on several AI models you can switch between and compare, such as Claude Haiku 5.5, Gemini 3.5 Flash-Lite, GPT-6 Luna and more.

  • AIFreeForever's API Generator is free to use.
  • No login, no sign up for your first few messages.
  • After that, you may be asked to verify your email with a one-time code.
Backend developer building REST API endpoints from the free API Generator: coder at a desk with monitors seen from behind, checking notes

How to Use API Generator

Follow these simple steps to use the ai api generator:

  1. 1

    Type the endpoint in the chat box, with the resource and its fields, such as a user registration endpoint with email and password.

  2. 2

    Pick the framework and the language on the settings card, and a framework brings its own language with it.

  3. 3

    Add needs such as JWT authentication, a PostgreSQL or MongoDB database, or pagination in the same chat box.

  4. 4

    Press Generate API Code, and the code opens with a comment listing each endpoint, its body and its status codes.

  5. 5

    Copy the code or download it as a file of the language, set the environment variables, and test it on a development server.

The REST API Endpoint PlannerFree PDF with the HTTP methods and the status codes each one returns. It also includes a request template for the API Generator, a security checklist before production and a one-page endpoint plan to fill in. Download free PDF

Frameworks and Languages for Your API

AIFreeForever's API Generator writes Express.js, FastAPI and Spring Boot code that follows each framework's own style.

Node.js

Express.js

A Node.js server file with JSON body parsing, the routes and an error-handling middleware.

Python

FastAPI

Pydantic models for request bodies and HTTPException status codes, ready to run with uvicorn.

Python

Django REST

A serializer that validates input, a view or ViewSet and the urls, in marked file sections.

Python

Flask

An app.py with routes, request JSON checks and jsonify error handlers.

C#

ASP.NET

An ApiController with route attributes, DataAnnotations validation and ActionResult types.

Java

Spring Boot

A RestController with Bean Validation, ResponseEntity status codes and a RestControllerAdvice for errors.

Ruby

Ruby on Rails

An API-mode controller with strong parameters, model validations and JSON renders.

PHP

Laravel

A controller with request validation rules and JSON responses.

Go

Gin

A main.go with request structs, binding tags and JSON responses.

Examples of Content Generated by API Generator

Here are some examples of what you can create with our tool. The four code samples are real API code made by AIFreeForever's API Generator. They cover a JWT authentication API in Express.js and product CRUD endpoints in FastAPI. The other two are a file upload API in Django REST Framework and a payment processing endpoint in Spring Boot. Backend developers can use them as starting points.

User authentication API with JWT in Express.js

110 lines
Express.jsNode.js
/*
 * User authentication API with JWT (Express.js, in-memory user store).
 *
 * Endpoints:
 *   POST /api/users - register a new user.
 *     Body: {"email": "...", "password": "..."}
 *     Responses: 201 {"id","email"} | 400 {"error"} | 409 {"error"} | 500 {"error"}
 *   POST /api/login - log in and receive a JWT.
 *     Body: {"email": "...", "password": "..."}
 *     Responses: 200 {"token"} | 400 {"error"} | 401 {"error"} | 500 {"error"}
 *   GET /api/me - current user's profile (JWT required).
 *     Header: Authorization: Bearer <token>
 *     Responses: 200 {"id","email"} | 401 {"error"} | 500 {"error"}
 *
 * Env vars: JWT_SECRET (required), PORT (optional, default 3000).
 */

const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());

const JWT_SECRET = process.env.JWT_SECRET;
if (!JWT_SECRET) {
  console.error('JWT_SECRET environment variable is required');
  process.exit(1);
}

const SALT_ROUNDS = 10;
// In-memory store: replace with real database calls (e.g. a users table or collection).
const users = [];
let nextId = 1;

// Trim, type-check and validate the request body.
function validateCredentials(body) {
  const email = typeof body.email === 'string' ? body.email.trim().toLowerCase() : '';
  const password = typeof body.password === 'string' ? body.password : '';
  if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    return { error: 'A valid email is required' };
  }
  if (password.length < 8) {
    return { error: 'Password must be at least 8 characters' };
  }
  return { email, password };
}

// POST /api/users - register.
app.post('/api/users', async (req, res, next) => {
  try {
    const v = validateCredentials(req.body);
    if (v.error) return res.status(400).json({ error: v.error });
    if (users.some((u) => u.email === v.email)) {
      return res.status(409).json({ error: 'Email already registered' });
    }
    const passwordHash = await bcrypt.hash(v.password, SALT_ROUNDS);
    const user = { id: nextId++, email: v.email, passwordHash }; // persist passwordHash in your DB
    users.push(user);
    return res.status(201).json({ id: user.id, email: user.email });
  } catch (err) {
    next(err);
  }
});

// POST /api/login - issue a JWT.
app.post('/api/login', async (req, res, next) => {
  try {
    const v = validateCredentials(req.body);
    if (v.error) return res.status(400).json({ error: v.error });
    const user = users.find((u) => u.email === v.email);
    // Same generic message for unknown email and wrong password.
    const ok = user && (await bcrypt.compare(v.password, user.passwordHash));
    if (!ok) return res.status(401).json({ error: 'Invalid email or password' });
    const token = jwt.sign({ sub: String(user.id), email: user.email }, JWT_SECRET, { expiresIn: '1h' });
    return res.json({ token });
  } catch (err) {
    next(err);
  }
});

// Middleware: require a valid Bearer token.
function requireAuth(req, res, next) {
  const header = req.headers.authorization || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!token) return res.status(401).json({ error: 'Missing bearer token' });
  try {
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}

// GET /api/me - protected profile.
app.get('/api/me', requireAuth, (req, res) => {
  return res.json({ id: req.user.sub, email: req.user.email });
});

// 404 for unknown routes.
app.use((req, res) => res.status(404).json({ error: 'Not found' }));

// Error-handling middleware: log server-side, never send the stack trace.
app.use((err, req, res, next) => {
  console.error(err);
  return res.status(500).json({ error: 'Internal server error' });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Auth API listening on port ${PORT}`));

Product CRUD endpoints in FastAPI

114 lines
FastAPIPython
"""Product CRUD REST API built with FastAPI.

Endpoints (all responses are JSON):
  GET    /products           Query: skip (int >= 0, default 0), limit (int 1-100, default 50).
                             200 -> [Product]
  POST   /products           Body: {"name": str 1-100, "description": str <= 500,
                             "price": number > 0, "in_stock": bool (default true)}.
                             201 -> Product | 409 -> {"error": "..."} duplicate name | 422 -> {"error": "..."}
  GET    /products/{id}      200 -> Product | 404 -> {"error": "..."}
  PUT    /products/{id}      Body: same as POST. 200 -> Product | 404 | 409 | 422
  DELETE /products/{id}      204 no content | 404 -> {"error": "..."}
  Any unhandled error -> 500 -> {"error": "Internal server error"} (no stack trace).

Run: uvicorn main:app --reload
"""

from typing import Optional
from uuid import uuid4

from fastapi import FastAPI, HTTPException, Query, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, field_validator
from starlette.exceptions import HTTPException as StarletteHTTPException

# --- Request/response models: Pydantic validates and sanitises every body ---

class ProductCreate(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    description: str = Field(default="", max_length=500)
    price: float = Field(gt=0)
    in_stock: bool = True

    @field_validator("name", "description")
    @classmethod
    def strip_text(cls, value: str) -> str:
        # Sanitise: trim surrounding whitespace before storing.
        return value.strip()

class ProductOut(BaseModel):
    id: str
    name: str
    description: str
    price: float
    in_stock: bool

app = FastAPI(title="Product API")

# In-memory store: {product_id: {"id": ..., "name": ..., ...}}.
# Replace the dict reads/writes below with database calls here, e.g.
# SQLAlchemy/SQLModel session queries or parameterised SQL (asyncpg/psycopg).
_db: dict[str, dict] = {}

# --- Error handlers: every failure comes back as {"error": "..."} ---

@app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse:
    return JSONResponse(status_code=exc.status_code, content={"error": str(exc.detail)})

@app.exception_handler(RequestValidationError)
async def validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:
    details = "; ".join(
        "{}: {}".format(".".join(map(str, err["loc"][1:])) or "body", err["msg"])
        for err in exc.errors()
    )
    return JSONResponse(status_code=422, content={"error": details})

@app.exception_handler(Exception)
async def unexpected_error(request: Request, exc: Exception) -> JSONResponse:
    # Log exc server-side if needed; never leak stack traces to clients.
    return JSONResponse(status_code=500, content={"error": "Internal server error"})

def _ensure_unique(name: str, exclude_id: Optional[str] = None) -> None:
    for pid, product in _db.items():
        if pid != exclude_id and product["name"].lower() == name.lower():
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="A product with this name already exists",
            )

@app.post("/products", response_model=ProductOut, status_code=status.HTTP_201_CREATED)
def create_product(payload: ProductCreate) -> dict:
    _ensure_unique(payload.name)
    product_id = uuid4().hex
    _db[product_id] = {"id": product_id, **payload.model_dump()}
    return _db[product_id]

@app.get("/products", response_model=list[ProductOut])
def list_products(
    skip: int = Query(0, ge=0),
    limit: int = Query(50, ge=1, le=100),
) -> list:
    return list(_db.values())[skip:skip + limit]

@app.get("/products/{product_id}", response_model=ProductOut)
def get_product(product_id: str) -> dict:
    product = _db.get(product_id)
    if product is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")
    return product

@app.put("/products/{product_id}", response_model=ProductOut)
def replace_product(product_id: str, payload: ProductCreate) -> dict:
    if product_id not in _db:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")
    _ensure_unique(payload.name, exclude_id=product_id)
    _db[product_id] = {"id": product_id, **payload.model_dump()}
    return _db[product_id]

@app.delete("/products/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_product(product_id: str) -> None:
    if product_id not in _db:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")
    del _db[product_id]

File upload API in Django REST Framework

157 lines
Django RESTPython
# File upload API - Django REST Framework (Python 3).
#
# Endpoints (router mounts them under /api/):
#   GET    /api/files/       -> 200 OK with a JSON list of uploaded files.
#   POST   /api/files/       -> 201 Created. Body: multipart/form-data, field "file".
#                            -> 400 {"error": "..."} on missing, oversized or disallowed files.
#   GET    /api/files/{id}/  -> 200 OK with one file record; 404 {"error": "..."} if missing.
#   DELETE /api/files/{id}/  -> 204 No Content; 404 {"error": "..."} if missing.
#   Any unexpected failure -> 500 {"error": "Internal server error."} (no stack trace).
#
# Metadata is stored through the Django ORM (SQLite below for development; swap the
# DATABASES block for PostgreSQL or MySQL in production). Uploaded files are saved on
# disk under MEDIA_ROOT. Create the app first: python manage.py startapp uploads

# --- settings.py (relevant parts only) ---
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY", "dev-only-insecure-key")
DEBUG = os.environ.get("DJANGO_DEBUG", "1") == "1"

INSTALLED_APPS = [
    "django.contrib.contenttypes",
    "django.contrib.auth",
    "rest_framework",
    "uploads",
]

# SQLite for development. In production, read NAME/USER/PASSWORD from env variables.
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

MEDIA_URL = "/media/"
MEDIA_ROOT = os.environ.get("MEDIA_ROOT", str(BASE_DIR / "media"))

REST_FRAMEWORK = {
    "EXCEPTION_HANDLER": "uploads.views.custom_exception_handler",
    "DEFAULT_PARSER_CLASSES": [
        "rest_framework.parsers.MultiPartParser",
        "rest_framework.parsers.FormParser",
    ],
    "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
}

# --- uploads/models.py ---
from django.db import models

class UploadedFile(models.Model):
    file = models.FileField(upload_to="uploads/%Y/%m/")
    original_name = models.CharField(max_length=255)
    size = models.BigIntegerField()
    content_type = models.CharField(max_length=100)
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.original_name

# --- uploads/serializers.py ---
import os

from django.utils.text import get_valid_filename
from rest_framework import serializers

from .models import UploadedFile

MAX_FILE_SIZE = 5 * 1024 * 1024  # 5 MB
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".pdf", ".txt", ".csv"}

class UploadedFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UploadedFile
        fields = ["id", "file", "original_name", "size", "content_type", "uploaded_at"]
        read_only_fields = ["id", "original_name", "size", "content_type", "uploaded_at"]

    def validate_file(self, value):
        if value.size > MAX_FILE_SIZE:
            raise serializers.ValidationError("File exceeds the 5 MB limit.")
        extension = os.path.splitext(value.name)[1].lower()
        if extension not in ALLOWED_EXTENSIONS:
            raise serializers.ValidationError("This file type is not allowed.")
        return value

    def create(self, validated_data):
        upload = validated_data["file"]
        content_type = getattr(upload, "content_type", "") or "application/octet-stream"
        # Sanitise the stored filename; Django also de-duplicates names on disk.
        upload.name = get_valid_filename(upload.name)
        return UploadedFile.objects.create(  # ORM insert
            file=upload,
            original_name=upload.name,
            size=upload.size,
            content_type=content_type,
        )

# --- uploads/views.py ---
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler

from .models import UploadedFile
from .serializers import UploadedFileSerializer

def custom_exception_handler(exc, context):
    """Turn every DRF error into {"error": "..."} and hide unexpected failures."""
    response = drf_exception_handler(exc, context)
    if response is not None:
        data = response.data
        if isinstance(data, dict):
            parts = [
                " ".join(str(item) for item in value)
                if isinstance(value, (list, tuple))
                else str(value)
                for value in data.values()
            ]
            message = "; ".join(parts) or "Request failed."
        else:
            message = str(data)
        return Response({"error": message}, status=response.status_code)
    # Non-DRF exception: answer with a plain 500, no stack trace in the body.
    return Response(
        {"error": "Internal server error."},
        status=status.HTTP_500_INTERNAL_SERVER_ERROR,
    )

class UploadedFileViewSet(viewsets.ModelViewSet):
    queryset = UploadedFile.objects.all().order_by("-uploaded_at")  # ORM query
    serializer_class = UploadedFileSerializer
    http_method_names = ["get", "post", "delete", "head", "options"]

# --- uploads/urls.py ---
from rest_framework.routers import DefaultRouter

from .views import UploadedFileViewSet

router = DefaultRouter()
router.register(r"files", UploadedFileViewSet, basename="uploadedfile")

urlpatterns = router.urls

# --- project/urls.py ---
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include, path

urlpatterns = [
    path("api/", include("uploads.urls")),
]

# In production, serve MEDIA_ROOT from your web server or object storage instead.
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Payment processing endpoint in Spring Boot

179 lines
Spring BootJava
/*
 * Payment processing API - Spring Boot (Java 17+), single-file demo.
 *
 * Endpoints (JSON, base path /api/payments):
 *
 * POST /api/payments
 *   Body: {"amount": 19.99, "currency": "USD", "cardToken": "tok_visa_1234", "reference": "order-42"}
 *   Optional header: Idempotency-Key (max 64 chars)
 *   201 Created -> payment JSON
 *   400 Bad Request -> {"error": "..."} (validation or malformed body)
 *   409 Conflict -> {"error": "..."} (Idempotency-Key reused)
 *   500 -> {"error": "internal server error"}
 *
 * GET /api/payments/{id}
 *   200 OK -> payment JSON
 *   404 Not Found -> {"error": "payment not found"}
 *
 * POST /api/payments/{id}/refund
 *   200 OK -> payment JSON with status REFUNDED
 *   404 Not Found -> {"error": "payment not found"}
 *   409 Conflict -> {"error": "..."} (already refunded or not captured)
 *
 * Data lives in memory; swap the marked lines for a Spring Data repository
 * or parameterised JDBC. Card data must arrive only as a gateway token,
 * never a raw card number.
 */
package com.example.payments;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

record PaymentRequest(
    @NotNull @DecimalMin("0.01") @Digits(integer = 12, fraction = 2) BigDecimal amount,
    @NotBlank @Size(max = 3) @Pattern(regexp = "[A-Z]{3}") String currency,
    @NotBlank @Size(max = 255) @Pattern(regexp = "[A-Za-z0-9_-]{8,255}") String cardToken,
    @Size(max = 140) String reference) {
  PaymentRequest { // normalise inputs before validation
    currency = currency == null ? null : currency.trim().toUpperCase(Locale.ROOT);
    cardToken = cardToken == null ? null : cardToken.trim();
    reference = reference == null ? null : reference.trim();
  }
}

record Payment(Long id, BigDecimal amount, String currency, String cardToken,
               String status, Instant createdAt) {}

class ApiException extends RuntimeException {
  final HttpStatus status;
  ApiException(HttpStatus status, String message) {
    super(message);
    this.status = status;
  }
}

@SpringBootApplication
public class PaymentApiApplication {
  public static void main(String[] args) {
    SpringApplication.run(PaymentApiApplication.class, args);
  }
}

@RestController
@RequestMapping("/api/payments")
class PaymentController {

  // In-memory store: swap for a Spring Data repository (e.g. PaymentRepository
  // extends JpaRepository<Payment, Long>) or parameterised JDBC at the marks.
  private final Map<Long, Payment> payments = new ConcurrentHashMap<>();
  private final AtomicLong nextId = new AtomicLong(1);
  private final Set<String> idempotencyKeys = ConcurrentHashMap.newKeySet();

  // Gateway credential comes from the environment; never hard-code secrets.
  @Value("${PAYMENT_GATEWAY_KEY:}")
  private String gatewayKey;

  @PostMapping
  ResponseEntity<Payment> create(@Valid @RequestBody PaymentRequest req,
      @RequestHeader(value = "Idempotency-Key", required = false) String idemKey) {
    if (idemKey != null && idemKey.length() > 64) {
      throw new ApiException(HttpStatus.BAD_REQUEST, "Idempotency-Key too long");
    }
    if (idemKey != null && !idempotencyKeys.add(idemKey)) {
      throw new ApiException(HttpStatus.CONFLICT, "Idempotency-Key already used");
    }
    // TODO: replace with the real PSP SDK call (e.g. Stripe PaymentIntents),
    // passing gatewayKey; a token ending in "-fail" simulates a decline.
    String status = req.cardToken().endsWith("-fail") ? "DECLINED" : "CAPTURED";
    Payment payment = new Payment(nextId.getAndIncrement(), req.amount(),
        req.currency(), mask(req.cardToken()), status, Instant.now());
    payments.put(payment.id(), payment); // <- repository.save(payment) goes here
    return ResponseEntity.status(HttpStatus.CREATED).body(payment);
  }

  @GetMapping("/{id}")
  Payment get(@PathVariable Long id) {
    return find(id); // <- repository.findById(id) goes here
  }

  @PostMapping("/{id}/refund")
  Payment refund(@PathVariable Long id) {
    Payment payment = find(id);
    if (!"CAPTURED".equals(payment.status())) {
      throw new ApiException(HttpStatus.CONFLICT, "only captured payments can be refunded");
    }
    // TODO: call the gateway refund endpoint here with gatewayKey.
    Payment refunded = new Payment(payment.id(), payment.amount(), payment.currency(),
        payment.cardToken(), "REFUNDED", payment.createdAt());
    payments.put(id, refunded); // <- repository.save(refunded) goes here
    return refunded;
  }

  private Payment find(Long id) {
    return Optional.ofNullable(payments.get(id))
        .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "payment not found"));
  }

  private String mask(String token) {
    return "****" + token.substring(Math.max(token.length() - 4, 0));
  }
}

@RestControllerAdvice
class ApiExceptionHandler {

  private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);

  @ExceptionHandler(ApiException.class)
  ResponseEntity<Map<String, String>> apiException(ApiException ex) {
    return ResponseEntity.status(ex.status).body(Map.of("error", ex.getMessage()));
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  ResponseEntity<Map<String, String>> invalidBody(MethodArgumentNotValidException ex) {
    String detail = ex.getBindingResult().getFieldErrors().stream()
        .map(e -> e.getField() + ": " + e.getDefaultMessage())
        .collect(Collectors.joining("; "));
    return ResponseEntity.badRequest().body(Map.of("error", detail));
  }

  @ExceptionHandler(HttpMessageNotReadableException.class)
  ResponseEntity<Map<String, String>> unreadable(HttpMessageNotReadableException ex) {
    return ResponseEntity.badRequest().body(Map.of("error", "malformed JSON body"));
  }

  @ExceptionHandler(MethodArgumentTypeMismatchException.class)
  ResponseEntity<Map<String, String>> badPathVar(MethodArgumentTypeMismatchException ex) {
    return ResponseEntity.badRequest().body(Map.of("error", "invalid path parameter"));
  }

  // Log the real cause server-side; never return a stack trace to the client.
  @ExceptionHandler(Exception.class)
  ResponseEntity<Map<String, String>> unexpected(Exception ex) {
    log.error("unhandled error", ex);
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .body(Map.of("error", "internal server error"));
  }
}

Frequently Asked Questions

Why Choose AIFreeForever's API Generator?

When you need a working endpoint fast, AIFreeForever's API Generator writes the code for you for free.

Free to Use Generate API code with no payment and no account for your first messages.
Seven Frameworks Pick Express.js, FastAPI, Spring Boot and more, each with its usual language.
Documented Endpoints Every file opens with a comment listing the method, path, body and responses.
REST Conventions Get proper status codes like 201 Created and 204, plus input validation.
Safe Secrets Passwords are hashed and secrets are read from environment variables.
Download as a File Save your code as a .js, .py, .java or .go file in one click.

Tips from the developers of the free AIFreeForever AI tools

Describe your endpoint in full: name the resource and its fields in the request. Tell the API Generator which database and kind of authentication you need, such as JWT. Test every endpoint on a development server with curl or Postman before production.

Generate free API code from the free API Generator: two programmers discussing framework choice at a table with a server rack behind them

Generate Free API Code

Pick your framework and language, describe the endpoint you need, and AIFreeForever's API Generator writes the API code for free.

Express.jsFastAPISpring Boot

Related Developer Tools

By the AIFreeForever Research Team Last updated