Module 03 · Lesson 3.3
Connecting REST APIs and Internal Services
On this page
- What you will learn
- What is an API, and what is a REST API?
- Wrap an API in a narrow tool function
- Return only the fields the agent needs
- Turn HTTP errors into clear error messages
- A narrow REST tool in Python, run offline
- The same pattern works for internal company services
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Think of a restaurant. You do not walk into the kitchen and cook. You tell the waiter what you want, and the waiter brings back a plate. An API works like that waiter. One program asks, another program answers, and neither needs to know how the other works inside.
An AI agent that can only talk is not much help to a bike shop. It needs real facts, such as where an order is right now. In this lesson you learn the basics of web APIs in plain words. Then you learn how to give an agent safe access to one through a small, narrow tool. Most of it needs no coding. One short Python example runs fully offline.
What you will learn
- Explain an API, an endpoint, a GET request, a status code and a JSON response in plain words.
- Wrap one API call in a narrow tool function with a fixed address and a timeout.
- Return only the few fields the agent needs, instead of the whole response.
- Turn HTTP errors into short error messages the model can understand.
Before you start
- The previous lesson, Designing Tool Schemas and Validating Arguments.
- The earlier lessons in this module, especially How Tool Calling Works.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What is an API, and what is a REST API?
An API is a way for one program to ask another program for something. Back in the restaurant, the menu lists what you may order. The waiter carries your request in and the answer back out. You never see the kitchen.
Most web APIs speak a shared language called HTTP. It is the same language your browser uses to load a web page. A REST API is a web API that follows a common, simple style over HTTP. Each thing, such as an order, has its own address.
- Endpoint
- A web address that does one job. For example,
/orders/QF-1042means "give me order QF-1042". - Request
- The message your program sends to the API. It says what you want.
- GET request
- A request that only reads. It is like looking at a shelf. It changes nothing.
- Status code
- A number in the reply that says how it went. 200 means success. 404 means "not found". 500 means the server had a problem.
- JSON
- A plain text format for data, written as named fields. Example:
{"status": "dispatched"}. Both people and programs can read it.
Here is one full round trip for the Quillfeather Cycles shop. The program sends GET /orders/QF-1042. The API replies with status code 200 and a JSON body that holds the order.
{
"order_id": "QF-1042",
"status": "dispatched",
"estimated_delivery": "2026-11-18",
"customer_email": "sam@example.com",
"warehouse_notes": "Shelf B7, fragile frame"
}A typical reply body. Notice how much more it holds than an agent needs.
Wrap an API in a narrow tool function
The model never calls the API itself. It asks for a tool, and your code runs the tool. So the tool is the place where you decide what is allowed. Make it narrow: one job, and nothing extra.
A good habit is to think of the tool as a window with a small opening. The model can look through it, but it cannot climb in.
Five rules for a narrow tool
- One job.
lookup_orderreads one order. It does not also cancel or refund. - A fixed base address. The web address is written in your code. The model never types or picks a URL.
- Only the parameters the model may set. Here that is just
order_id, and you check its format first. - A timeout. If the API does not answer within a few seconds, stop waiting.
- Bounded output. Return only the fields the agent needs, never the whole reply.
- Agent
Asks for lookup_order QF-1042
- Tool function
Checks the ID, adds the fixed address
- REST API
Returns the full JSON order
- Bounded result
Only status and delivery date
Your tool code sits in the middle. It checks what goes out and trims what comes back.
Return only the fields the agent needs
Look at the JSON from the first section again. The agent needs two facts: the status and the delivery date. The email and the warehouse notes are extra.
Extra fields cost you in three ways. They use up space in the model's context. They can leak private data into a reply. And they give the model more to get confused about. This is the "share the minimum" idea from Context Design: What the Agent Needs at Each Step.
| Field in the API reply | Does the agent need it? | Why |
|---|---|---|
| status | Yes | It answers "where is my order?" |
| estimated_delivery | Yes | It answers "when will it arrive?" |
| customer_email | No | Private data. It could leak into a reply. |
| warehouse_notes | No | Internal detail. It only adds noise. |
For long lists, bound the size too. Return the first five results and a count, not five hundred rows.
Turn HTTP errors into clear error messages
APIs fail in many ways. An order may not exist. The server may crash. The network may be down. Your tool should not crash. It should catch the problem and return a short error observation, a small result that tells the model what went wrong.
| What happened | Status code | What the tool returns |
|---|---|---|
| The order was found | 200 | {"status": "dispatched", "estimated_delivery": "2026-11-18"} |
| No such order | 404 | {"error": "order not found"} |
| The API crashed | 500 | {"error": "order service failed"} |
| No answer in time, or no network | none | {"error": "order service unavailable"} |
| The ID has the wrong format | not sent | {"error": "invalid order id"} |
Why not pass the full error along? It is long, it can reveal internal details, and it does not help the model decide what to do. A clear message lets the agent say "I could not find that order" or hand over to a person. A later lesson, Tool Errors, Retries, Timeouts and Idempotency, goes deeper into what to do after a failure.
A narrow REST tool in Python, run offline
You do not need a real shop to try this. The script starts a tiny fake Quillfeather orders API on your own computer. Then the lookup_order tool talks to it. It uses only Python's built-in tools. Python's own docs say http.server is for demos and not for production, which is fine here.
import json, re, threading, urllib.error, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
ORDERS = {"QF-1042": {"order_id": "QF-1042", "status": "dispatched",
"estimated_delivery": "2026-11-18", "customer_email": "sam@example.com",
"warehouse_notes": "Shelf B7, fragile frame"}}
class FakeOrdersApi(BaseHTTPRequestHandler):
def do_GET(self):
order = ORDERS.get(self.path.removeprefix("/orders/"))
self.send_response(200 if order else 404)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(order or {"detail": "no such order"}).encode())
def log_message(self, *args):
pass # keep the console quiet
server = HTTPServer(("127.0.0.1", 0), FakeOrdersApi) # port 0: the OS picks a free port
threading.Thread(target=server.serve_forever, daemon=True).start()
BASE_URL = f"http://127.0.0.1:{server.server_port}" # fixed in code, never set by the model
def lookup_order(order_id):
if not re.fullmatch(r"QF-[0-9]{4}", str(order_id)):
return {"error": "invalid order id"}
try:
with urllib.request.urlopen(f"{BASE_URL}/orders/{order_id}", timeout=5) as resp:
data = json.load(resp)
except urllib.error.HTTPError as err:
return {"error": "order not found" if err.code == 404 else "order service failed"}
except OSError:
return {"error": "order service unavailable"}
return {"status": data["status"], "estimated_delivery": data["estimated_delivery"]}
print(lookup_order("QF-1042"))
print(lookup_order("QF-9999"))
server.shutdown()Offline and standard library only. Run it with python order_api_tool.py.
What each part does
ORDERSis made-up data that the fake API serves. It holds extra fields on purpose.FakeOrdersApiis the fake API.do_GETanswers GET requests with the order as JSON, or with code 404 when there is no such order.log_messagedoes nothing, so the server prints no log lines and the output stays clean.HTTPServer(("127.0.0.1", 0), ...)listens on your own computer only. Port 0 asks the system to pick a free port.threading.Thread(...)runs the server in the background, so the script can carry on and call it.BASE_URLis the fixed address. The model can never change it.re.fullmatch(...)checks the ID has the shapeQF-plus four digits. Bad IDs stop here, and no request is sent.urlopen(..., timeout=5)calls the API and gives up after five seconds.exceptlines turn a 404, another HTTP error, or a network problem into a short error message.- The last
returnkeeps onlystatusandestimated_delivery. The email and warehouse notes are dropped. server.shutdown()stops the fake server.
{'status': 'dispatched', 'estimated_delivery': '2026-11-18'}
{'error': 'order not found'}The first result has two fields, even though the API sent five. The second shows a 404 turned into a plain error observation. This is the real-API version of the lookup_order you built with an in-memory dictionary in Practical Lab: Build and Test Your First AI Agent, Step by Step. The agent's side does not change at all.
The same pattern works for internal company services
A company often has many internal services. These are programs only staff systems may call, such as a stock service, a customer database or a returns system. Many of them are REST APIs too.
Treat them in exactly the same way. Write a narrow tool, fix the address, set a timeout and return only what the agent needs. Internal does not mean safe. Internal services often hold more private data than public ones, so the trimming matters even more.
- For reading, such as
lookup_order, use GET and keep the tool read-only. - For changing things, such as
request_return, create a request that staff must approve. Do not let the agent finish the change alone. - Give each tool its own small job. Do not build one tool that can call any internal address.
Conclusion and your next step
An API is a waiter between two programs. A tool is your safe window onto it. Give the tool one job, a fixed address, a timeout, trimmed output and short error messages, and the agent gets real facts without getting real power.
Your next step: take any free or fake API you know and write down a narrow tool for it, using the five rules above. Then continue to Authentication, Secrets and Least-Privilege Access, where you learn how to prove who is calling without leaking keys.
For more, see the Practical Lab: Build an Agent That Uses Two Tools or the Glossary of AI Engineering and Agent Terms. If a real call fails in odd ways, try Troubleshooting LLM API Errors.
Common errors and how to fix them
The model's reply mentions a customer's email or a warehouse note.
Why it happens: The tool returned the whole API response.
Fix: Return only the fields the agent needs, and build the result yourself field by field.
The whole agent freezes while waiting for an order.
Why it happens: The request has no timeout, so a slow API holds it forever.
Fix: Always set a timeout, such as timeout=5, and return an error observation when it passes.
The agent says "something went wrong" and gives up.
Why it happens: A 404 and a 500 both became the same vague error.
Fix: Map each case to its own short message, such as "order not found" and "order service failed".
A test fails with a connection error on the first call.
Why it happens: The fake server was not started yet, or a fixed port was already in use.
Fix: Start the server before calling the tool. Use port 0 so the system picks a free one.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Wrap a stock-check API in a narrow tool
Quillfeather Cycles has a fake stock API at GET /stock/BELL-01 that returns JSON with sku, quantity, supplier_cost and shelf_location. Write a check_stock(sku) tool plan, or extend the Python script, so the agent learns only whether the item is in stock.
You will need
- SKUs look like BELL-01 (letters, a dash, two digits).
- Unknown SKUs return status code 404.
- The agent needs only the quantity. Supplier cost is private.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Copy the shape of
lookup_orderand change the pattern, path and returned field. - Build the result with a new dictionary instead of returning the response.
- Handle
HTTPErrorbeforeOSError, because the first is a kind of the second.
Show a model answer
A good answer keeps the same five rules. Define a fixed BASE_URL. Check the SKU with a pattern such as [A-Z]+-[0-9]{2}. Call /stock/ plus the SKU with timeout=5. If the call works, return {"quantity": data["quantity"]} only. If it raises HTTPError with code 404, return {"error": "item not found"}. For any other HTTP code, return {"error": "stock service failed"}. For network problems, return {"error": "stock service unavailable"}. Supplier cost and shelf location never leave the function, so they can never leak into the model's reply.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A fixed address limits the tool to one service, which keeps its power small. Speed is not the reason, which is why the first option is tempting but wrong. Models can read addresses fine, so the third option is also wrong. The risk is what they might be tricked into calling.
Show the answer and explanation
Answer: B. Trimming in code is certain, because private fields never reach the model. Asking the model to ignore data is tempting but unreliable, and the data still fills the context and can leak into a reply.
Show the answer and explanation
Answer: A. A short, clear message tells the model what happened and lets it respond well. A full error page is long and can reveal internal details. Returning nothing leaves the model guessing, and it may repeat the same failing call.
Frequently asked questions
What is the difference between an API and a REST API?
"API" is the wide idea: any way for one program to ask another for something. A REST API is one common kind. It works over the web using HTTP, and each thing, such as an order, has its own address. Most web APIs you will meet are REST APIs.
What do HTTP status codes like 200, 404 and 500 mean?
They are short numbers that say how a request went. 200 means it worked. 404 means the thing you asked for was not found. 500 means the server had a problem of its own. Codes starting with 4 usually mean the request was wrong, and codes starting with 5 mean the server failed.
Why should an AI agent never get the raw API response?
Raw responses are often long and full of fields the agent does not need. Some of those fields are private. Sending them costs context space and risks leaking data into replies. A tool that trims the output keeps answers short and safe.
How is calling an internal company service different from a public API?
The pattern is the same: a narrow tool, a fixed address, a timeout and trimmed output. The difference is the risk. Internal services often hold more private data, so you should be even stricter about what the tool returns and what it is allowed to do.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- An overview of HTTP(opens in a new tab)
MDN Web Docs · Official documentation · Background on how requests and responses work.
- HTTP response status codes(opens in a new tab)
MDN Web Docs · Official documentation · A list of status codes and what each one means.
- Python standard library: urllib.request(opens in a new tab)
Python Software Foundation · Official documentation · Reference for the request function and its timeout setting.
- http.server: HTTP servers(opens in a new tab)
Python Software Foundation · Official documentation · Reference for the small server used in the example. It warns the module is not for production.
- Writing effective tools for agents(opens in a new tab)
Anthropic · Official documentation · Advice on designing tools that agents can use well.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP Foundation · Official documentation · Why tools should give an agent only the power its job needs.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.