Skip to content

A JSON API

This program handles requests like GET /products/2. It returns the product with that number as JSON. If there is no such product, it returns the status 404.

<?nvs
// This program is a small JSON API. It returns one product, found by its number.
#[Core\Json\Derive]
class Product
{
public uint $id;
public string $name;
public float $price;
public function constructor(uint $id, string $name, float $price)
{
$this->id = $id;
$this->name = $name;
$this->price = $price;
}
}
class Products
{
// The route connects a request like `GET /products/2` to this method.
#[Core\Route(path: '/products/{id}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public static function show(uint $id): void
{
array<Product> $all = [new Product(1, 'Fig', 3.5), new Product(2, 'Apple', 0.4)];
foreach ($all as Product $product) {
if ($product->id == $id) {
Core\Response::sendJson($product);
return;
}
}
Core\Response::setStatus(404);
Core\Response::sendJson({ error: 'no such product' });
}
}
// The gate checks each request before a route method runs, and it writes the errors as JSON.
class Gate implements Core\Router\Gate
{
public function allows(Core\Router\Match $route): bool
{
return $route->accessAs<Core\Audience>() == Core\Audience::Public;
}
// `dispatch` has already set the status, such as 404 for a path with no route.
public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void
{
Core\Response::sendJson({ error: 'not possible' });
}
public function failed(?Core\Router\Match $route, ?Throwable $error): void
{
Core\Response::sendJson({ error: 'server error' });
}
}
// `dispatch` finds the route for the request and calls its method.
Core\Router::dispatch(new Gate());
nvs serve (HTTP Server Response)
{"id":2,"name":"Apple","price":0.4}

The output above is the response to GET /products/2.

Start the server with nvs serve json-api.nvs. Then open http://127.0.0.1:8000/products/2 in your browser, or run this command:

Terminal window
curl http://127.0.0.1:8000/products/2

#[Core\Route] connects the path /products/{id} to the method Products::show. {id} is a part of the path that can change. Core\Router::dispatch finds the route that matches the request and calls its method.

dispatch converts {id} to the type of the parameter $id. The type is uint, a whole number that is not negative.

Gate is a class of your own. Its method allows runs before Products::show, and the method runs only when allows returns true. refused writes the response when no route method can run, for example for a path with no route. dispatch has already set the status, such as 404. failed writes the response when a route method throws an error.

#[Core\Json\Derive] lets Novis turn a Product into JSON. Core\Response::sendJson sends the JSON text as the response.

#[Core\Access] says who may call the route. Core\Audience::Public means everyone may call it.

Core\Json::encode and Core\Json::decodeAs work with the whole document in memory. For a list that can be very long, use Core\Json::encodeEach and Core\Json::decodeEach. They write and read one element at a time, so the memory your program uses stays the same at any size.

<?nvs
// This program writes a list of products to a JSON file, then reads it back one product at a time.
#[Core\Json\Derive]
class Product
{
public uint $id;
public string $name;
public function constructor(uint $id, string $name)
{
$this->id = $id;
$this->name = $name;
}
}
// A generator creates each product only when `encodeEach` needs the next one.
class Catalog
{
public static function products(): Iterator<Product>
{
yield new Product(1, 'Fig');
yield new Product(2, 'Apple');
yield new Product(3, 'Pear');
}
}
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'products.json');
// `encodeEach` returns the JSON text in pieces. `writeStream` writes each piece to the file.
Core\IO::writeStream($path, Core\Json::encodeEach(Catalog::products()), { overwrite: true });
// `decodeEach` reads one element of the array, checks it as a `Product`, and gives it to the loop.
Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);
foreach (Core\Json::decodeEach<Product>($file) as Product $product) {
echo $product->id, ' ', $product->name, "\n";
}
$file->close();
Output
1 Fig
2 Apple
3 Pear

encodeEach takes the next product only when it needs it. It returns the JSON text in pieces of up to 64 KiB, and Core\IO::writeStream writes them to the file. You can also write the pieces to a response with Core\Response::startStream.

decodeEach reads from an open file or from the request body, Core\Request::bodyStream(). Each element is checked like a document that decodeAs reads. A second argument such as '/items' selects an array inside the document. { lines: true } reads JSON Lines, one value on each line.