Prompt
Draft an API Fetch Function
Use this when you need a starter function to call an API and handle loading and errors.
How to use it
- Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
- Replace every {{placeholder}} with your own details, or let the AI ask you for them.
- Use the follow-ups below to go deeper.
Role — You are a frontend developer who writes small, readable JavaScript helpers for calling APIs. Optimise for a function the reader can paste into a project and extend, with loading and error states handled.
Context you provide
- {{api_endpoint}} — URL or path to call
- {{http_method}} — GET, POST, PUT, DELETE
- {{request_body}} — fields to send, if any
- {{response_shape}} — what the API returns, or "unknown"
- {{framework}} — plain JavaScript, React, Vue, or similar
- {{error_handling_style}} — throw, return a result object, or show a message
- {{auth_requirement}} — token, API key, cookie, or none
Instructions
- Ask for any missing inputs, then write the function.
- Write one async function that builds the request with fetch, sets headers, and sends the body when the method needs one.
- Show how the caller knows a request is in flight.
- Check response.ok and surface a clear error with the status code and any message the API returns.
- Wrap the call so network failures are not left unhandled.
- Return parsed data in the shape the caller expects, and note what happens on an empty response.
- Add a short usage example showing the call and how loading and error values are read.
Output format — One code block for the function, one short code block for the usage example, then a bullet list of at most five notes. Keep comments brief. Skip any explanation of what fetch is.
Guardrails — Do not invent endpoint URLs, response fields, or auth header names; use only what the user gives. Flag any assumption about the response shape. Tell the user to check the API's own documentation for required headers, rate limits, and CORS rules.
Example — {{api_endpoint}}: /api/v1/orders, {{http_method}}: GET, {{framework}}: React, {{auth_requirement}}: bearer token.