RESTful API
APIs follow specifications
Conventional endpoints for documentation
Models read the docs
LLMs understand and implement the API calls
C/S operations
Agent access the endpoints
Introduction
RESTful APIs provide endpoint interface for external software to access their services. RESTful APIs support information exchange and task performance by secure, reliable, and efficient software communication standards.
However, how to use the RESTful APIs generally requires reading API documentations before users can leverage. OpenAPI specification fills this gap. It specifies the conventional information standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation.
Many AI tools support this pattern and agentic identification and utilization. For example, GPT actions empower their users to interact with external applications via RESTful API calls on ChatGPT.
For more details, please visit the above links to know more about them.
Interaction model
An OpenAPI document that conforms to the OpenAPI Specification could be shown to users via Swagger UI. An OpenAPI Description (OAD) formally describes the surface of an API and its semantics in JSON and YAML formats.
Scaffold code
A minimal, working FastAPI scaffold with auto-generated OpenAPI documentation.
from typing import Dict, List, Optional
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
# 1. Initialize FastAPI with OpenAPI metadata
app = FastAPI(
title="Scaffold API",
description="A minimal, working FastAPI scaffold with auto-generated OpenAPI documentation.",
version="0.1.0",
openapi_url="/openapi.json", # Default OpenAPI schema endpoint
docs_url="/docs", # Swagger UI
)
# 2. Define Pydantic models (automatically translated to OpenAPI schemas)
class ItemBase(BaseModel):
name: str = Field(..., min_length=1, examples=["Widget"])
description: Optional[str] = Field(None, examples=["A standard utility widget."])
price: float = Field(..., gt=0, examples=[19.99])
class ItemCreate(ItemBase):
pass
class Item(ItemBase):
id: int = Field(..., examples=[1])
# In-memory store for scaffold purposes
db: Dict[int, Item] = {
1: Item(id=1, name="Sample Item", description="Initial seeded item", price=9.99)
}
# 3. Define routes
@app.get("/items", response_model=List[Item], tags=["Items"], summary="List all items")
def list_items() -> List[Item]:
return list(db.values())
@app.get("/items/{item_id}", response_model=Item, tags=["Items"], summary="Get an item by ID")
def get_item(item_id: int) -> Item:
if item_id not in db:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
return db[item_id]
@app.post(
"/items",
response_model=Item,
status_code=status.HTTP_201_CREATED,
tags=["Items"],
summary="Create a new item",
)
def create_item(payload: ItemCreate) -> Item:
new_id = max(db.keys(), default=0) + 1
item = Item(id=new_id, **payload.model_dump())
db[new_id] = item
return item
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)The server produces the API documents on
- interactive documents on
/docsfor humans - comprehensive documents on
/openapi.jsonfor AI
{
"openapi": "3.1.0",
"info": {
"title": "Scaffold API",
"description": "A minimal, working FastAPI scaffold with auto-generated OpenAPI documentation.",
"version": "0.1.0"
},
"paths": {
"/items": {
"get": {
"tags": [
"Items"
],
"summary": "List all items",
"operationId": "list_items_items_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item"
},
"type": "array",
"title": "Response List Items Items Get"
}
}
}
}
}
},
"post": {
"tags": [
"Items"
],
"summary": "Create a new item",
"operationId": "create_item_items_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ItemCreate"
}
}
},
"required": true
},
"responses": {
"201": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
},
"/items/{item_id}": {
"get": {
"tags": [
"Items"
],
"summary": "Get an item by ID",
"operationId": "get_item_items__item_id__get",
"parameters": [
{
"name": "item_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"title": "Item Id"
}
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail"
}
},
"type": "object",
"title": "HTTPValidationError"
},
"Item": {
"properties": {
"name": {
"type": "string",
"minLength": 1,
"title": "Name",
"examples": [
"Widget"
]
},
"description": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Description",
"examples": [
"A standard utility widget."
]
},
"price": {
"type": "number",
"exclusiveMinimum": 0,
"title": "Price",
"examples": [19.99]
},
"id": {
"type": "integer",
"title": "Id",
"examples": [1]
}
},
"type": "object",
"required": [
"name",
"price",
"id"
],
"title": "Item"
},
"ItemCreate": {
"properties": {
"name": {
"type": "string",
"minLength": 1,
"title": "Name",
"examples": [
"Widget"
]
},
"description": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"title": "Description",
"examples": [
"A standard utility widget."
]
},
"price": {
"type": "number",
"exclusiveMinimum": 0,
"title": "Price",
"examples": [19.99]
}
},
"type": "object",
"required": [
"name",
"price"
],
"title": "ItemCreate"
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [
{
"type": "string"
},
{
"type": "integer"
}
]
},
"type": "array",
"title": "Location"
},
"msg": {
"type": "string",
"title": "Message"
},
"type": {
"type": "string",
"title": "Error Type"
},
"input": {
"title": "Input"
},
"ctx": {
"type": "object",
"title": "Context"
}
},
"type": "object",
"required": [
"loc",
"msg",
"type"
],
"title": "ValidationError"
}
}
}
}The above code block demonstrates the API documents in json satisfying the OpenAPI Description (OAD).
Code example
This lesson has no running example. FastAPI is a server framework, and the demonstrations on this site execute entirely in the browser.
To try this pattern, run the scaffold code in your own environment and prompt a model the OpenAPI endpoints the server publishes.