NuGet Client SDK

The NuGet Client SDK refers to a group of NuGet packages:

  • NuGet.Indexing - NuGet's indexing library for the Visual Studio client search functionality.
  • NuGet.Commands - Complete commands common to command-line and GUI NuGet clients.
  • NuGet.Common - Common utilities and interfaces for all NuGet libraries.
  • NuGet.Configuration - NuGet's configuration settings implementation.
  • NuGet.Credentials - NuGet client's authentication models.
  • NuGet.DependencyResolver.Core - NuGet's PackageReference dependency resolver implementation.
  • NuGet.Frameworks - NuGet's understanding of target frameworks.
  • NuGet.LibraryModel - NuGet's types and interfaces for understanding dependencies.
  • NuGet.Localization - NuGet localization package.
  • NuGet.PackageManagement - NuGet Package Management functionality for Visual Studio installation flow.
  • NuGet.Packaging - Provides a set of APIs to interact with .nupkg and .nuspec files from a stream. NuGet.Protocol depends on this package.
  • NuGet.ProjectModel - NuGet's core types and interfaces for PackageReference-based restore, such as lock files, assets file and internal restore models.
  • NuGet.Protocol - Provides a set of APIs interact with HTTP and file-based NuGet feeds.
  • NuGet.Resolver - NuGet's dependency resolver for packages.config based projects.
  • NuGet.Versioning - NuGet's implementation of Semantic Versioning.

You can find the source code for these packages in the NuGet/NuGet.Client GitHub repository.

Note

For documentation on the NuGet server protocol, please refer to the NuGet Server API.

Support policy

All security bugs should be reported to the Microsoft Security Response Center (MSRC) at MSRC's report page. Also, see the security policy in the NuGet.Client repo.

We do not guarantee API stability, as our team's responsibility is tooling, not libraries. See the NuGet SDK documentation in the NuGet.Client repo for more information.

NuGet.Protocol

Install the NuGet.Protocol package to interact with HTTP and folder-based NuGet package feeds:

dotnet add package NuGet.Protocol

You can find the source code for these examples on the NuGet.Protocol.Samples project on GitHub.

Tip

Repository.Factory is defined in the NuGet.Protocol.Core.Types namespace, and the GetCoreV3 method is an extension method defined in the NuGet.Protocol namespace. Therefore, you will need to add using statements for both namespaces.

List package versions

Find all versions of Newtonsoft.Json using the NuGet V3 Package Content API:

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;

SourceCacheContext cache = new SourceCacheContext();
SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
FindPackageByIdResource resource = await repository.GetResourceAsync<FindPackageByIdResource>();

IEnumerable<NuGetVersion> versions = await resource.GetAllVersionsAsync(
    "Newtonsoft.Json",
    cache,
    logger,
    cancellationToken);

foreach (NuGetVersion version in versions)
{
    Console.WriteLine($"Found version {version}");
}

Download a package

Download Newtonsoft.Json v12.0.1 using the NuGet V3 Package Content API:

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;

SourceCacheContext cache = new SourceCacheContext();
SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
FindPackageByIdResource resource = await repository.GetResourceAsync<FindPackageByIdResource>();

string packageId = "Newtonsoft.Json";
NuGetVersion packageVersion = new NuGetVersion("12.0.1");
using MemoryStream packageStream = new MemoryStream();

await resource.CopyNupkgToStreamAsync(
    packageId,
    packageVersion,
    packageStream,
    cache,
    logger,
    cancellationToken);

Console.WriteLine($"Downloaded package {packageId} {packageVersion}");

using PackageArchiveReader packageReader = new PackageArchiveReader(packageStream);
NuspecReader nuspecReader = await packageReader.GetNuspecReaderAsync(cancellationToken);

Console.WriteLine($"Tags: {nuspecReader.GetTags()}");
Console.WriteLine($"Description: {nuspecReader.GetDescription()}");

Get package metadata

Get the metadata for the "Newtonsoft.Json" package using the NuGet V3 Package Metadata API:

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;

SourceCacheContext cache = new SourceCacheContext();
SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
PackageMetadataResource resource = await repository.GetResourceAsync<PackageMetadataResource>();

IEnumerable<IPackageSearchMetadata> packages = await resource.GetMetadataAsync(
    "Newtonsoft.Json",
    includePrerelease: true,
    includeUnlisted: false,
    cache,
    logger,
    cancellationToken);

foreach (IPackageSearchMetadata package in packages)
{
    Console.WriteLine($"Version: {package.Identity.Version}");
    Console.WriteLine($"Listed: {package.IsListed}");
    Console.WriteLine($"Tags: {package.Tags}");
    Console.WriteLine($"Description: {package.Description}");
}

Search packages

Search for "json" packages using the NuGet V3 Search API:

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;

SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
PackageSearchResource resource = await repository.GetResourceAsync<PackageSearchResource>();
SearchFilter searchFilter = new SearchFilter(includePrerelease: true);

IEnumerable<IPackageSearchMetadata> results = await resource.SearchAsync(
    "json",
    searchFilter,
    skip: 0,
    take: 20,
    logger,
    cancellationToken);

foreach (IPackageSearchMetadata result in results)
{
    Console.WriteLine($"Found package {result.Identity.Id} {result.Identity.Version}");
}

Push a package

Push a package using the NuGet V3 Push and Delete API:

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;

SourceCacheContext cache = new SourceCacheContext();
SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
PackageUpdateResource resource = await repository.GetResourceAsync<PackageUpdateResource>();

string apiKey = "my-api-key";

await resource.Push(
    "MyPackage.nupkg",
    symbolSource: null,
    timeoutInSecond: 5 * 60,
    disableBuffering: false,
    getApiKey: packageSource => apiKey,
    getSymbolApiKey: packageSource => null,
    noServiceEndpoint: false,
    skipDuplicate: false,
    symbolPackageUpdateResource: null,
    logger);

Delete a package

Delete a package using the NuGet V3 Push and Delete API:

Note

NuGet servers are free to interpret a package delete request as a "hard delete", "soft delete", or "unlist". For example, nuget.org interprets the package delete request as an "unlist". For more information about this practice, see the Deleting Packages policy.

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;

SourceCacheContext cache = new SourceCacheContext();
SourceRepository repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
PackageUpdateResource resource = await repository.GetResourceAsync<PackageUpdateResource>();

string apiKey = "my-api-key";

await resource.Delete(
    "MyPackage",
    "1.0.0-beta",
    getApiKey: packageSource => apiKey,
    confirm: packageSource => true,
    noServiceEndpoint: false,
    logger);

Work with authenticated feeds

Use NuGet.Protocol to work with authenticated feeds.

ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;
SourceCacheContext cache = new SourceCacheContext();
var sourceUri = "https://contoso.privatefeed/v3/index.json";
var packageSource = new PackageSource(sourceUri)
{
    Credentials = new PackageSourceCredential(
        source: sourceUri,
        username: "myUsername",
        passwordText: "myVerySecretPassword",
        isPasswordClearText: true,
        validAuthenticationTypesText: null)
};
// If the `SourceRepository` is created with a `PackageSource`, the rest of APIs will consume the credentials attached to `PackageSource.Credentials`.
SourceRepository repository = Repository.Factory.GetCoreV3(packageSource);
PackageMetadataResource resource = await repository.GetResourceAsync<PackageMetadataResource>();

IEnumerable<IPackageSearchMetadata> packages = await resource.GetMetadataAsync(
    "MyPackage",
    includePrerelease: true,
    includeUnlisted: false,
    cache,
    logger,
    cancellationToken);

foreach (IPackageSearchMetadata package in packages)
{
    Console.WriteLine($"Version: {package.Identity.Version}");
    Console.WriteLine($"Listed: {package.IsListed}");
    Console.WriteLine($"Tags: {package.Tags}");
    Console.WriteLine($"Description: {package.Description}");
}

NuGet.Packaging

Install the NuGet.Packaging package to interact with .nupkg and .nuspec files from a stream:

dotnet add package NuGet.Packaging

Create a package

Create a package, set metadata, and add dependencies using NuGet.Packaging.

Important

It is strongly recommended that NuGet packages are created using the official NuGet tooling and not using this low-level API. There are a variety of characteristics important for a well-formed package and the latest version of tooling helps incorporate these best practices.

For more information about creating NuGet packages, see the overview of the package creation workflow and the documentation for official pack tooling (for example, using the dotnet CLI).

PackageBuilder builder = new PackageBuilder();
builder.Id = "MyPackage";
builder.Version = new NuGetVersion("1.0.0-beta");
builder.Description = "My package created from the API.";
builder.Authors.Add("Sample author");
builder.DependencyGroups.Add(new PackageDependencyGroup(
    targetFramework: NuGetFramework.Parse("netstandard1.4"),
    packages: new[]
    {
        new PackageDependency("Newtonsoft.Json", VersionRange.Parse("10.0.1"))
    }));

using FileStream outputStream = new FileStream("MyPackage.nupkg", FileMode.Create);
builder.Save(outputStream);
Console.WriteLine($"Saved a package to {outputStream.Name}");

Read a package

Read a package from a file stream using NuGet.Packaging.

using FileStream inputStream = new FileStream("MyPackage.nupkg", FileMode.Open);
using PackageArchiveReader reader = new PackageArchiveReader(inputStream);
NuspecReader nuspec = reader.NuspecReader;
Console.WriteLine($"ID: {nuspec.GetId()}");
Console.WriteLine($"Version: {nuspec.GetVersion()}");
Console.WriteLine($"Description: {nuspec.GetDescription()}");
Console.WriteLine($"Authors: {nuspec.GetAuthors()}");

Console.WriteLine("Dependencies:");
foreach (var dependencyGroup in nuspec.GetDependencyGroups())
{
    Console.WriteLine($" - {dependencyGroup.TargetFramework.GetShortFolderName()}");
    foreach (var dependency in dependencyGroup.Packages)
    {
        Console.WriteLine($"   > {dependency.Id} {dependency.VersionRange}");
    }
}

Console.WriteLine("Files:");
foreach (var file in reader.GetFiles())
{
    Console.WriteLine($" - {file}");
}

Third-party documentation

You can find examples and documentation for some of the API in the following blog series by Dave Glick, published 2016:

Note

These blog posts were written shortly after the 3.4.3 version of the NuGet client SDK packages were released. Newer versions of the packages may be incompatible with the information in the blog posts.

Martin Björkström did a follow-up blog post to Dave Glick's blog series where he introduces a different approach on using the NuGet Client SDK to install NuGet packages: