Turn your PostgreSQL database directly into a RESTful API with .NET Core.
-
Add postgrest.net NuGet to your project.
-
Add
AddPostgRest()
to your MVC builder configuration, like this:
services.AddMvc().AddPostgRest();
-
Specify default database connection any way you like, by either:
- a) Injecting
NpgsqlConnection
into your services - b) Specifying
Connection
parameter in optionsAddPostgRest(new PostgRestOptions{Connection = '<connection name or connection string value>'});
- c) Add new configuration section
"PostgRest": { "Connection": "<connection name or connection string value>" }
- a) Injecting
-
Add some PostgreSQL functions to your database.
Now, when you run you application all function that have default naming convention (name starts with rest_{get|post|put|delete}
) are turned automatically into RESTful endpoints.
- Add following function to your PostgreSQL database:
create function rest__get_values(_id int) returns text as
$$
begin
return (
select "value"
from "values"
where id = _id
);
end
$$ language plpgsql;
- Run your application. Notice following info log on startup in your application console:
info: PostgRest.net.FeatureProvider[0]
Mapping PostgreSQL routine "function rest__get_values(IN _id integer) returns text" to REST API endpoint "GET api/values/{_id}/" ...
- You can also map query string values or body values (either json or multipart form) to your PostgreSQL function parameters.
By convention if parameter name contains
body
orquery
(this is configurable) it will be mapped to body or query string respectively. For example, if you include_body
parameter in function, you may see following info log in your application console:
info: PostgRest.net.FeatureProvider[0]
Mapping PostgreSQL routine "function rest__put_values(/*from body*/IN _body json) returns json" to REST API endpoint "PUT api/values/" ...
- Also, in spirit of full integration, any log executed inside your PostgreSQL routine (
raise info
, etc) - will be treated as normal part of .NET core logging.
Checkout full, working examples in examples directory of this repository
Also, you may consult unit tests directory for different usage examples.
Copyright (c) Vedran Bilopavlović. This source code is licensed under the MIT license.