Register

Quanty · Agentic AI

Go API Templates

A Go API starter is useful when you need a small service or testable handler that accepts a well-defined input and returns a predictable response. It is not a complete broker service or a ready-to-run trading system. This guide explains how to request a local template, test its interface, and review the code before adding an upstream connection. Quanty Code is in testing (beta). QuantPower is software, not an adviser.

1. Define the interface before asking for an implementation

Begin with a job whose input, output and failure cases fit on a page. A health example might return a fixed JSON response to show that the process is running. A quote summary might compute minimum, maximum and count from a small array of fictional prices. A local catalog might look up a sample symbol in memory. All three can be checked without calling a broker, reading a real account, or making a trading decision.

Say which example you want and what it must not include. “Build a Go API that accepts a JSON array of fictional prices, returns a count and range, rejects empty or malformed input, and runs only on loopback” is more useful than “build an API for trading.” You can give examples of a valid response and a refused request. Add a test that checks each response so it is easy to tell whether a later edit changed the contract.

Keep the interface smaller than the service you might someday build. Do not add account records, session state, a database or outbound network calls if the first job is only a calculation. A small offline handler does not prove that the same program is ready for customer data or changing market conditions. It proves that the inputs and outputs you chose can be reviewed. You can still add real responsibilities later in separate, documented steps.

A good brief also explains when the result is available. A synchronous handler returns its result within the request. A task that may run longer could need a different interface, but a queue adds statuses, storage and failure modes. Do not call a local example asynchronous unless it really has that behavior. Keep the model simple enough that another person can describe it without reading every line.

2. Choose plain routes and explicit methods

Use names that tell the next person what each route does. A local read-only health route can simply report that the process answered the request. A path that summarizes a body of fictional values can use the method appropriate to that contract. Avoid reusing a name that implies live market access for a route that only reads a static fixture. Include the chosen method and a representative request in the instructions.

Handle an unexpected method deliberately. It is easy to leave a handler accepting methods it was never meant to process. A method test can verify that the handler returns a refusal and avoids running the core calculation. If you return a list of allowed methods, check it against the route's real behavior. Do not add a second endpoint simply because another common starter includes it. Each endpoint is more surface area to validate and maintain.

Keep URL fields small and predictable. A source identifier in a path may be different from a query parameter or a value inside a body. Write down which form the route reads and how it handles a missing field, repeated parameter or unknown field. If a sample allows a small enumerated set, checking membership is usually easier to reason about than accepting every possible string. Tests can show which choices were designed, rather than inferred from a working request.

Use public, fictional labels in local examples. If a lookup says “NIFTY sample,” its response should be marked fictional and should not be presented as an exchange quote. A health route is likewise not a legal or operational guarantee. A simple process check can succeed even when the service cannot reach an upstream system. Name the check after what it actually verifies.

3. Decide what a valid body looks like

A small JSON contract is easier to maintain if it names fields and units. For a fictional price list, state whether the fields are rupees, paise or unitless demonstration values. If the contract uses integers, say why. A string and a number are not interchangeable simply because both look like the same digits in a log. Ask for a clear response if the caller sends an unexpected type.

Validate before calculation. If the example needs at least one row and at most a stated number, check those bounds. If it has a maximum allowed request size, enforce the size before attempting to store or parse an arbitrarily large body. The Go HTTP package documentation describes facilities for handling incoming requests and limiting what is read. A declared length in a request is not by itself equivalent to applying a read limit.

Decide how the example treats unknown fields. A closed contract may reject them, which helps catch misspelled keys. A deliberately extensible contract might keep ignoring certain additions. Either policy can make sense if it is explicit. Test that trailing content, nulls and unexpected nested structures follow the same rules as written in the documentation, rather than depending on a decoder behavior nobody checked.

Reject values that cannot be meaningfully combined. A large array of arbitrary numbers may be syntactically valid but outside the needs of the sample. A timestamp with no offset may be invalid for a required timezone-aware contract. A quote that says it was observed later than the caller's declared current time may indicate mismatched clocks. The habit to build is not accepting more input; it is recognizing which input your calculation actually understands.

4. Keep handlers thin and the calculation independent

A useful handler turns an HTTP request into arguments, calls a function, and turns its result into a response. The function that calculates the output does not need to see headers, deadlines or remote addresses. It should receive the validated data it needs. This separation keeps a unit test focused on the rule or calculation and a handler test focused on mapping input to a status and body.

For a sample quote summary, one function can accept a validated slice and return the count and range. A handler can reject malformed input before calling it. If the same calculation later appears in a batch job or a command-line tool, you can reuse it without carrying the server along. When an output is wrong, you can test the calculation with a few hand-written values rather than launching the full program.

Keep side effects outside the calculation. A function that only summarizes values should not write to disk, contact a service or choose how to log failures. Where a service really does need an external dependency, pass it in explicitly. A fake implementation can then simulate success, refusal and timeout in the tests. Avoid building every behavior into a package-level variable that can be changed by unrelated code running in the same process.

Put names on the boundary so it is obvious to a reviewer. “Decode input,” “validate sample prices,” “summarize” and “write result” have different jobs. A catch-all function described as “process trading data” may be concise but hard to verify. Naming each part clearly also helps the person adapting the template see which piece can be replaced without changing the rest of the interface.

5. Write success and error responses as a small contract

A successful response should have the status and fields stated in the instructions. Set the content type for the body you actually return. A route that documents JSON should not return an HTML login page or an unstructured stack trace. Decide on a predictable error shape and show it using fictional input. Try not to embed every detail of the failure in the response; a simple error code and useful message are easier for the caller to handle.

Use statuses consistently. A malformed body, an unsupported method and a missing resource are different cases. The HTTP semantics standard explains the meaning of common statuses; your API can add documented error codes for its own contract. You can make examples easier to compare by asserting the status and decoding the body instead of matching an entire string that might change in formatting.

Choose which errors should be public. A user may benefit from being told that a required field is missing or that a request exceeds the documented size. They do not benefit from seeing a secret, a private server path or an entire account response. If logs hold more detail than the public message, keep those logs appropriate for their audience. Do not assume every error value is free of sensitive information.

When a handler calls a function that can fail, make the error mapping explicit. Avoid returning success just because the response can be formatted. Conversely, do not use a request error for a valid empty case unless the contract says the case is invalid. A client that cannot distinguish between these outcomes may show stale results or keep retrying a request it cannot fix.

6. Test the actual handler without running a general service

The Go testing HTTP package provides utilities for exercising handlers with representative requests and recording their responses. A small example can send a fictional request directly to the handler, inspect the status and decode its output. This does not require a real broker, an internet connection or a listening production server. Keep the test near the source so the next person can run it with the documented command.

Test a request from the perspective of a caller. Supply the method, path, body and headers that an actual use case expects. Check the response content type as well as the status when that matters to a downstream consumer. A handler can accidentally return the correct numeric result within the wrong format. The result might look fine in a terminal but fail when a program expects to parse it.

Add focused negative cases. A body that is too large, a wrong content type and invalid JSON need not reach the same stage of processing. A malformed number should not be silently treated as zero. A nested object should not pass if the contract wants a simple list. Try one boundary value at the accepted maximum and another just beyond it. Such pairs catch off-by-one mistakes that normal examples miss.

Do not use a test that forces success by bypassing the handler's boundary. Calling only the calculation function is useful, but it does not prove the request path checks its body or translates bad input correctly. Conversely, handler tests do not replace function tests for precise arithmetic. Keep both where they add signal. If the example intentionally lacks something such as real account authentication, say that in the test instructions rather than appearing to verify it.

7. Bound request size, time and work independently

A server can receive a short request that still asks for substantial work, or a large body whose eventual result is only one number. Size, time and work are separate dimensions. Choose bounded inputs for a local starter and explain why the limits are examples rather than universal limits suitable for every application. A handler that only summarizes fictional data does not need unbounded concurrency or a queue of anonymous work.

Check how the example reads the body. A limit applied after reading the entire body does not bound the memory already used to read it. A test can send a body larger than your policy and verify early refusal. Bound the number of decoded records as well if one input may hold many small values. Limiting either count or bytes alone answers only part of the question.

Time has several edges too. A server may wait for headers, for a body or for a calculation to return. It may also call a dependency that waits independently. Review how cancellation is passed through rather than inserting a timeout that does not reach the work. For a simulated task, a short deterministic fixture can prove that the handler notices cancellation. You do not need a real slow service to test the path.

Do not change safety bounds just because a prompt asks for arbitrary values. When a template should expose a setting, prefer a meaningful option such as a small local page size. Leave operational controls fixed or documented until they can be reviewed. If a requested setting is incompatible with the sample, it is better to say so than accept it and silently use the original behavior after the caller has left.

8. Use local fixtures, not accounts or market promises

Keep fictional data small enough that someone can recompute the sample by hand. A quote summary with four prices is a better first validation than a dump of a real account. Include decimal or boundary values if they affect the calculation. Make the purpose of each row visible, such as an item that falls exactly on a limit. The fixture should demonstrate what the code does, not look harder to understand than the real task.

Label fake responses where the person using the example will see them. “Fictional sample” in the instructions is useful, but a printed output copied from the terminal may lose that context. Include a label in the visible report when providing a demonstration. Do not dress a fake quote as a real one, even if the symbol is recognizable. A generated example cannot establish that a provider returned a specific price or that an order would be filled.

If the example has a client-facing page, avoid a working form that collects names, credentials or other information unless that collection is part of an approved plan. A display built from a fixture can still help test wording and layout. A field that cannot submit anything may still look like a real account control, so label it plainly or remove it. Scope should be apparent to a reader without requiring them to inspect the source.

A local fixture is useful when a provider is unavailable too. Keep its use explicit: switching to sample data is acceptable for a demonstration labelled as such, not for a data pipeline that is expected to produce live results. Decide what the real application should do when it cannot retrieve valid data. It may show a clear failure or the age of a previous result, but it should not silently replace the input with fiction.

9. Demonstrate pagination with a small experiment

A local catalog can show pagination without a real account. Begin with three fictional records in a stable order and a page size of two. The first page should contain two records and a token to request the next page. The second page should contain the last record and no continuation token. A test can prove those counts, order and end conditions through the actual handler.

Decide how invalid continuation values behave. The sample can refuse an unknown cursor rather than returning the first page again. Restarting silently may lead a caller through the same entries multiple times. If another exercise asks for page numbers instead, explain the different contract rather than changing the meaning of the same field. An API example should use one pagination policy clearly.

A fixture order should be reproducible. If you fetch sample records from a structure whose iteration order is not part of the contract, you may see a different result each run. Choose a stable sort or maintain a known list order, then check the boundary between pages. Record what happens if the final page is exactly full. The correct continuation behavior depends on whether another record actually exists, not just whether the current page reached its limit.

A local pagination demonstration does not prove behavior under updates or large datasets. If an application later serves mutable records, define what the cursor represents and how new, removed or updated items affect the sequence. A sample with public fixture labels is not a model for safely exposing an identifier tied to a real account. Keep the lessons about ordering and continuity separate from deployment and identity concerns.

10. Verify what the sample claims about readiness

A health route is often confused with readiness. A liveness example may simply show that a process can answer a request. It does not imply every dependency is reachable or that required data is loaded. A readiness check needs an explicit list of conditions and an agreed response when one fails. Use the terms your system actually supports and avoid expanding the promise just to make the response look reassuring.

When reviewing a template, read the instructions from a new user's perspective. If it says to run locally, confirm its default bind stays local. If it says no network calls, inspect the imports and code paths that would create one. If the sample includes a file for dependencies, note whether the normal setup must download them. A local standard-library example can be straightforward to run, but that does not turn it into an automatically deployed application.

Confirm whether the code can be stopped without leaving work behind. A synchronous minimal handler and a background task have different shutdown concerns. If the sample adds cancellation as an exercise, test the expected failure and make it clear whether the request was started, abandoned or completed. A user should not have to infer completion from silence after closing a terminal.

Compare the output and the code at the same revision. It is common for a preview screenshot to come from an earlier copy with different defaults. State the exact setup step that produces the result and rerun after you edit a file. If a teammate cannot reproduce the response using the files you gave them, the example is not ready for handoff even if it worked on your own machine.

11. Keep provider access out until the contract is stable

A starter can teach HTTP behavior without any broker connector. If your work later needs data, map the documented read operation into a separate adapter. Perform the first checks with a fictional response. Introduce credentials only through the appropriate private method for the account, never in the source, a prompt or a test file. Use only the operation and permissions required for the task.

Think about which data crosses the boundary. A route that accepts fictional prices would not need personal account information. Do not extend it to record unrelated fields because an upstream response happens to contain them. A small converter can return only the fields needed for the output. Whatever logs are kept should be suitable for their intended audience and should avoid private identifiers, credentials and complete responses unless a separate approved process requires them.

Plan how a refused or incomplete read affects the handler. You may need a documented, bounded wait and a safe way to reject unexpected responses. Do not treat a nonempty body as proof that an operation succeeded. Check the expected shape and distinguish an unavailable input from a valid empty result. These decisions should be visible to the caller, not buried in a catch-all error message.

Keep order actions out of the starter. A read example, a handler that summarizes user-supplied data and a service that affects an account have different responsibilities. A successful offline test does not grant permission to use a broker or tell you how an order would behave. Treat any later connection as its own implementation and review.

12. Run and share a testable package

A useful package includes the source, module information where needed, tests and a short set of instructions. State which command performs the local test and which runs the demonstration, if those are different. Use a separate directory rather than assuming the recipient has the same files on their computer. Make success visible in a simple response they can inspect, and give them one intentional error to try.

Run the same checks on the package that will be shared. This catches missing files, a renamed module or a test that only passed because an unrelated file was present on your machine. Record which commands passed and anything that was not exercised. “Local handler tests passed” is a useful report. “Production ready” is not justified by a fixture. Note the distinction rather than making the handoff sound broader than it is.

If the package is adapted from Quanty Code, say which parts came from a template and which parts changed. An optional setting such as a page size is easier to review than a new provider, but either should have a test that would fail when the change is omitted. Keep the earlier working example available for comparison. When a failure appears, compare inputs and outputs with the most direct fixture before changing several layers at once.

Finish the review with three questions. Can another person run it without private access? Can that person check one success and one failure? Can they tell where the example ends and a future integration begins? If the answer to any is no, make that boundary or instruction clearer. QuantPower is software, not an adviser. Use the starter to understand and test your own requirements, not to infer market outcomes.

13. Trace a request from the caller to the response

A helpful review exercise is to write the journey of a single request in order. The caller chooses the local address and sends the approved method. The handler checks whether the route and method match, then reads at most the allowed body. A decoder turns the body into the expected structure. A validator rejects missing fields before passing data to the summary function. The handler writes one response with the relevant status, content type and body. If a step fails, follow the failure branch instead of continuing to the calculation.

Take one situation and test where it stops. Imagine a request with an otherwise correct body but an unsupported method. The desired result should be visible before reading input or running the computation. A second request could have an allowed method and a malformed number. That case should make it to input validation and stop there. A success case should reach the independent calculation function and return the expected count. Using the same data in these three requests makes it harder to accidentally attribute a difference to the fixture.

The next review should cover how a caller identifies the expected response. If it looks at the HTTP status only, it may miss a malformed body. If it looks at the body only, a short error could be parsed as an empty result. The client can check both and retain the internal error category as appropriate. A sample request and response pair beside the command can clarify the assumptions without making the instructions longer than the example code itself.

14. Make the review record useful for the next change

Describe the difference between changing a presentation field and changing a contract. For example, adding an explanatory message to a sample output may be harmless for a person reading it, while changing a numeric field into formatted text could break a caller. Removing a pagination field changes how the caller knows whether to continue. Renaming an error category changes how it decides whether to seek new input or retry. These changes can be demonstrated with local tests and do not require a real connection.

If someone asks to adapt the code for a new job, start by editing the one-sentence contract rather than pasting a second, unrelated handler into the same file. Confirm whether the new job shares the request methods, types and error policy. If it needs real data, record where the data is expected to come from and which responsibilities remain separate. Then use a small fixture to prove the change you made is the change the caller sees.

A change note can be as short as “Only the allowable sample page size changed; unsupported input is still refused, and the downstream response shape is unchanged.” Add a targeted test that would fail on the old behavior and rerun the basic valid and invalid cases. When you share the new package, include which version of the package you checked and which features are still hypothetical. The next developer should be able to distinguish tested template behavior from extrapolation based on an idea or a screenshot.

Explore Quanty Code