Function registerRestInterface

Generates registers a REST interface and connects it the the given instance.

Each method is mapped to the corresponing HTTP verb. Property methods are mapped to GET/PUT and all other methods are mapped according to their prefix verb. If the method has no known prefix, POST is used. The following table lists the mappings from prefix verb to HTTP verb:

PrefixHTTP verb
getGET
queryGET
setPUT
putPUT
updatePATCH
patchPATCH
addPOST
createPOST
postPOST

A method named 'index' is mapped to the root URL (e.g. GET /api/). If a method has its first parameter named 'id', it will be mapped to ':id/method' and 'id' is expected to be part of the URL instead of a JSON request. Parameters with default values will be optional in the corresponding JSON request.

Any interface that you return from a getter will be made available with the base url and its name appended.

Prototype

void registerRestInterface(T)(URLRouter router, T instance, string urlPrefix = "/", MethodStyle style = MethodStyle.lowerUnderscored)(
  URLRouter router,
  ReturnTypeString.T instance,
  string urlPrefix,
  MethodStyle style
);

Examples

The following example makes MyApi available using HTTP requests. Valid requests are:

import vibe.d;

interface IMyItemsApi {
	string getText();
	int getIndex(int id);
}

interface IMyApi {
	string getStatus();

	@property string greeting();
	@property void greeting(string text);

	void addNewUser(string name);
	@property string[] users();
	string[] index();
	string getName(int id);

	@property IMyItemsApi items();
}

class MyItemsApiImpl : IMyItemsApi {
	string getText() { return "Hello, World"; }
	int getIndex(int id) { return id; }
}

class MyApiImpl : IMyApi {
	private string m_greeting;
	private string[] m_users;
	private MyItemsApiImpl m_items;

	this() { m_items = new MyItemsApiImpl; }

	string getStatus() { return "OK"; }

	@property string greeting() { return m_greeting; }
	@property void greeting(string text) { m_greeting = text; }

	void addNewUser(string name) { m_users ~= name; }
	@property string[] users() { return m_users; }
	string[] index() { return m_users; }
	string getName(int id) { return m_users[id]; }

	@property MyItemsApiImpl items() { return m_items; }
}

static this()
{
	auto routes = new URLRouter;

	registerRestInterface(routes, new MyApiImpl, "/api/");

	listenHTTP(new HTTPServerSettings, routes);
}

See Also

RestInterfaceClient class for a seamless way to acces such a generated API

Authors

Sönke Ludwig, Михаил Страшун

Copyright

© 2012 RejectedSoftware e.K.

License

Subject to the terms of the MIT license, as written in the included LICENSE.txt file.