Skip to content

otherdeniz/NginxApiClient

Repository files navigation

NginxApiClient

A comprehensive C# client library for the NGINX Proxy Manager REST API.

License: MIT

Features

  • Full API coverage — all 11 NPM resource groups (proxy hosts, certificates, redirection hosts, dead hosts, streams, access lists, users, settings, audit log, reports)
  • Multi-target — supports .NET Framework 4.8 through .NET 9 via sub-package architecture
  • Async-first — all methods are async with CancellationToken support
  • Transparent authentication — JWT token lifecycle managed automatically
  • Strongly-typed — typed request/response models with IntelliSense
  • TestableINginxProxyManagerClient interface for easy mocking
  • DI-readyIServiceCollection extension methods for ASP.NET Core
  • Version-aware — auto-detects the NPM server version and adapts the certificate API (NPM 2.12–2.15+)

Installation

Modern .NET (.NET 8 / .NET 9)

dotnet add package NginxApiClient
dotnet add package NginxApiClient.SystemTextJson

.NET Framework 4.8

Install-Package NginxApiClient
Install-Package NginxApiClient.NewtonsoftJson

Quick Start

using NginxApiClient;
using NginxApiClient.SystemTextJson;

// Create client
var serializer = new SystemTextJsonSerializer();
var options = new NginxProxyManagerClientOptions
{
    BaseUrl = "http://localhost:81",
    Credentials = new NginxCredentials("admin@example.com", "changeme"),
};

// Authentication is handled automatically
var client = NginxProxyManagerClientFactory.Create(options, serializer);

// List all proxy hosts
var hosts = await client.ProxyHosts.ListAsync();
foreach (var host in hosts)
{
    Console.WriteLine($"{host.Id}: {string.Join(", ", host.DomainNames)} -> {host.ForwardHost}:{host.ForwardPort}");
}

ASP.NET Core DI Registration

// In Program.cs or Startup.cs
services.AddNginxApiClient(options =>
{
    options.BaseUrl = "http://npm:81";
    options.Credentials = new NginxCredentials("admin@example.com", "changeme");
});

// Inject into your services
public class MyService
{
    private readonly INginxProxyManagerClient _npmClient;

    public MyService(INginxProxyManagerClient npmClient)
    {
        _npmClient = npmClient;
    }

    public async Task CreateProxyHostAsync(string domain, string backendHost, int backendPort)
    {
        await _npmClient.ProxyHosts.CreateAsync(new CreateProxyHostRequest
        {
            DomainNames = new List<string> { domain },
            ForwardScheme = "http",
            ForwardHost = backendHost,
            ForwardPort = backendPort,
            SslForced = true,
            Http2Support = true,
        });
    }
}

Create a Proxy Host with SSL

var proxyHost = await client.ProxyHosts.CreateAsync(new CreateProxyHostRequest
{
    DomainNames = new List<string> { "app.example.com" },
    ForwardScheme = "http",
    ForwardHost = "192.168.1.100",
    ForwardPort = 8080,
    SslForced = true,
    HstsEnabled = true,
    Http2Support = true,
    BlockExploits = true,
    AllowWebsocketUpgrade = true,
    CertificateId = 5,  // ID of an existing certificate
});

Console.WriteLine($"Created proxy host {proxyHost.Id} for {string.Join(", ", proxyHost.DomainNames)}");

Certificate Management

// List certificates and check expiry
var certs = await client.Certificates.ListAsync();
foreach (var cert in certs)
{
    var daysUntilExpiry = (cert.ExpiresOn - DateTime.UtcNow).Days;
    Console.WriteLine($"{cert.NiceName}: expires in {daysUntilExpiry} days");

    if (daysUntilExpiry < 30)
    {
        await client.Certificates.RenewAsync(cert.Id);
        Console.WriteLine($"  -> Renewed!");
    }
}

// Provision a new Let's Encrypt certificate
var newCert = await client.Certificates.CreateAsync(new CreateCertificateRequest
{
    DomainNames = new List<string> { "new.example.com" },
    Provider = "letsencrypt",
    // On NPM 2.13+ these are ignored (NPM uses the account email); see "NPM Version Compatibility".
    Meta = new CertificateMeta { LetsencryptEmail = "admin@example.com", LetsencryptAgree = true },
});

NPM Version Compatibility

NGINX Proxy Manager changed its certificate-creation schema in v2.13: the Let's Encrypt account email and terms agreement are no longer sent per-certificate (NPM reads the email from the authenticated user account and agrees to the terms automatically), and v2.14 added an optional key_type. Sending the old fields to a 2.13+ server returns HTTP 400 — data/meta must NOT have additional properties.

The client handles this for you. By default it auto-detects the server version (one cached, unauthenticated GET /api/ probe) and shapes the certificate payload to match:

NPM version NpmVersion Certificate meta behaviour
≤ 2.12 V2_12 sends letsencrypt_email + letsencrypt_agree
2.13 V2_13 omits both (email from account, agreement automatic)
≥ 2.14 (incl. 2.15) V2_14 omits both; supports key_type (rsa/ecdsa)
// Default — auto-detect (recommended). No configuration needed.
var options = new NginxProxyManagerClientOptions
{
    BaseUrl = "http://localhost:81",
    Credentials = new NginxCredentials("admin@example.com", "changeme"),
    // Version = NpmVersion.Auto,   // the default

    // Or pin the version explicitly to skip the detection probe:
    // Version = NpmVersion.V2_14,
};

If the probe fails (server unreachable or an unexpected response), the client falls back to the latest known generation rather than throwing.

Heads-up for NPM 2.13+: the Let's Encrypt account email must be set on the NPM user you authenticate as — it is no longer taken from CreateCertificateRequest. Any LetsencryptEmail/LetsencryptAgree you set are silently ignored on 2.13+. Setting KeyType while targeting a version below 2.14 throws NginxVersionCompatibilityException.

Error Handling

using NginxApiClient.Exceptions;

try
{
    var host = await client.ProxyHosts.GetAsync(999);
}
catch (NginxNotFoundException ex)
{
    Console.WriteLine($"Proxy host not found: {ex.ErrorDetail}");
}
catch (NginxAuthenticationException ex)
{
    Console.WriteLine($"Authentication failed: {ex.ErrorDetail}");
}
catch (NginxApiException ex)
{
    Console.WriteLine($"API error {ex.StatusCode}: {ex.ErrorDetail}");
}

Available Resource Clients

Property Interface Description
client.ProxyHosts IProxyHostClient Manage reverse proxy hosts
client.Certificates ICertificateClient Manage SSL certificates and Let's Encrypt
client.RedirectionHosts IRedirectionHostClient Manage URL redirections
client.DeadHosts IDeadHostClient Manage custom 404 pages
client.Streams IStreamClient Manage TCP/UDP stream forwarding
client.AccessLists IAccessListClient Manage IP and auth-based access restrictions
client.Users IUserClient Manage NPM users and permissions
client.Settings ISettingsClient Get/update NPM settings
client.AuditLog IAuditLogClient Read audit log entries
client.Reports IReportsClient Access host statistics

NUGET Packages

NUGET Package Target Purpose
NginxApiClient .NET Standard 2.0 Core interfaces, models, exceptions
NginxApiClient.SystemTextJson .NET 8, .NET 9 System.Text.Json serialization + DI
NginxApiClient.NewtonsoftJson .NET Standard 2.0 Newtonsoft.Json serialization + DI

Examples

See the examples/ folder for runnable console projects:

License

MIT License - see LICENSE for details.

About

NGINX Proxy Manager API Client for .NET

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors