Function registerRestInterface

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

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.

Prototypes

void registerRestInterface(TImpl)(
  URLRouter router,
  TImpl instance,
  string url_prefix,
  MethodStyle style
);

void registerRestInterface(TImpl)(
  URLRouter router,
  TImpl instance,
  MethodStyle style
);

See Also

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

Example

This is a very limited example of REST interface features. Please refer to the "rest" project in the "examples" folder for a full overview.

All details related to HTTP are inferred from the interface declaration.

interface IMyAPI
{
	// GET /api/greeting
	@property string greeting();

	version (none) {
		// PUT /api/greeting
		@property void greeting(string text);
	}

	// POST /api/users
	@path("/users")
	void addNewUser(string name);

	// GET /api/users
	@property string[] users();

	// GET /api/:id/name
	string getName(int id);
}

// vibe.d takes care of all JSON encoding/decoding
// and actual API implementation can work directly
// with native types

class API : IMyAPI
{
	private {
		string m_greeting;
		string[] m_users;
	}
	
	@property string greeting()
	{
		return m_greeting;
	}

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

	void addNewUser(string name)
	{
		m_users ~= name;
	}

	@property string[] users()
	{
		return m_users;
	}

	string getName(int id)
	{
		return m_users[id];
	}
}

// actual usage, this is usually done in app.d module
// constructor

void static_this()
{
	import vibe.http.server, vibe.http.router;

	auto router = new URLRouter();
	registerRestInterface(router, new API());
	listenHTTP(new HTTPServerSettings(), router);
}

Authors

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

Copyright

© 2012-2013 RejectedSoftware e.K.

License

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