A simple REST API that provides CRUD operations on a hero
object, it was built using C# and PostgreSQL.
1. Clone the application
git clone https://github.com/nicolaspearson/csharp.heroes.api.git
2. Start the database
docker-compose up
3. Migrations
Create the initial migrations, if they do not exist:
dotnet ef migrations add initial
Run the migrations:
dotnet ef database update
4. Build and run the app
dotnet run -c Debug --project ./src/HeroApi/HeroApi.csproj
The app will start running at http://localhost:8000
dotnet run -c Release --project ./src/HeroApi/HeroApi.csproj
The app will start running at http://localhost:8000
Below are details of how I created the Web Api
and Test
projects.
Create the src
directory:
mkdir src
Initialize the Web Api Project:
cd src
dotnet new webapi -o HeroApi
Add PostgreSQL packages:
cd ./src/HeroApi
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package NpgSql.EntityFrameworkCore.PostgreSQL.Design
Added connection string to appsettings.json
:
{
...
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Username=master;Password=masterkey;Database=hero;"
}
}
Connect to the database in the Startup
class:
...
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<HeroContext>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
...
}
...
Finally create your models, and controllers.
Create the test
directory:
mkdir test
Initialize the Test Project:
cd test
dotnet new xunit -o HeroApi.IntegrationTests
Add Testing packages:
cd ./test/HeroApi.IntegrationTests
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.AspNetCore.App
Add a Reference to the Web Api project:
cd ./test/HeroApi.IntegrationTests
dotnet add reference ../../src/HeroApi/HeroApi.csproj
Run the tests:
cd ./test/HeroApi.IntegrationTests
dotnet test
Check this article for a more detailed explanation.
The following endpoints are available:
GET /hero/{heroId}
GET /hero
POST /hero
PUT /hero/{heroId}
DELETE /hero/{heroId}
Run this command to benchmark request performance:
wrk -d1m http://localhost:8000/hero