- Learn to build a REST API with Couchbase’s C# SDK 3.4 and ASP.NET Minimal API
- See how you can fetch data from Couchbase using SQL++ queries
- Explore CRUD operations in action with Couchbase
In questo tutorial imparerai come connetterti a un cluster di Couchbase Capella per creare, leggere, aggiornare e cancellare documenti e come scrivere semplici query SQL++ parametrizzate.
Prerequisiti
Per eseguire questo progetto preconfigurato, avrete bisogno di:
- Couchbase Capella cluster with Travel-sample La carretta è carica.
- Per eseguire questo tutorial utilizzando un cluster di Couchbase gestito autonomamente, si prega di consultare la documentazione relativa al comando appendice.
- .NET SDK v6+ installed.
- Ensure that the .Net version is compatibile con il SDK di Couchbase.
- Code Editor installed (Visual Studio Professional, Visual Studio Code, or JetBrains Rider)
- Loading Travel Sample Bucket
- If travel-sample is not loaded in your Capella cluster, you can load it by following the instructions for your Capella Cluster:
Configurazione di Couchbase Capella
Quando si esegue Couchbase utilizzando Capella, Per poter utilizzare questo servizio, è necessario soddisfare i seguenti requisiti preliminari.
- L'applicazione richiede che il bucket dei campioni di viaggio sia caricato nel cluster della Capella UI.
- Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
Configurazione dell'applicazione
We will walk through the different steps required to get the application running.
Cloning Repo
git clone https://github.com/couchbase-examples/aspnet-quickstart-minapi.git
Installare le dipendenze
cd src/Couchbase.TravelSample
dotnet restore
Dependency Injection Nuget package
The Couchbase SDK for .NET includes a nuget package called Couchbase.Extensions.DependencyInjection which is designed for environments like ASP.NET that takes in a configuration to connect to Couchbase and automatically registers interfaces that you can use in your code to perform full CRUD (create, read, update, delete) operations and queries against the database.
Configurazione della database di configurazione
Per saperne di più su come connettersi al cluster Capella, si prega di seguire le istruzioni riportate nella pagina dedicata. istruzioni.
In particolare, è necessario fare quanto segue:
- Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
- Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.
All configuration for communication with the database is stored in the appsettings.Development.json file. This includes the connection string, username, password, bucket name and scope name. The default username is assumed to be Administrator and the default password is assumed to be P@$$w0rd12. If these are different in your environment you will need to change them before running the application.
"Couchbase": {
"BucketName": "travel-sample",
"ScopeName": "inventory",
"ConnectionString": "couchbases://yourassignedhostname.cloud.couchbase.com",
"Username": "Administrator",
"Password": "P@ssw0rd12",
"IgnoreRemoteCertificateNameMismatch": true,
"HttpIgnoreRemoteCertificateMismatch": true,
"KvIgnoreRemoteCertificateNameMismatch": true
}
Nota: La stringa di connessione prevede
couchbases://ocouchbase://parte.
Running The Application
Directly on Machine
In questo momento abbiamo installato le dipendenze, caricato i dati del travel-sample e configurato l'applicazione con le credenziali. L'applicazione è ora pronta e potete lanciarla.
cd src/Couchbase.TravelSample
dotnet run
Usare Docker
- Creare l'immagine Docker
cd aspnet-minapi-quickstart-travelsample
docker build -t couchbase-aspnet-minapi-quickstart .
- Run the docker image
cd aspnet-minapi-quickstart-travelsample
docker run -e DB_CONN_STR=<connection_string> -e DB_USERNAME=<user_with_read_write_permission_to_travel-sample_bucket> -e DB_PASSWORD=<password_for_user> -p 8080:8080 couchbase-aspnet-minapi-quickstart
You can access the Application on http://localhost:8080/swagger/index.html
Verificare l'applicazione
Una volta avviata l'applicazione, è possibile visualizzare i dettagli dell'applicazione nei log.

L'applicazione verrà eseguita sul port 8080 della macchina locale (http://localhost:8080/swagger/index.html). You will find the Swagger documentation of the API if you go to the URL in your browser. Swagger documentation is used in this demo to showcase the different API end points and how they can be invoked. More details on the Swagger documentation can be found in the appendice.

Modello dei dati
Per questo tutorial utilizzeremo tre collezioni:, aeroporto, aerolinea e itinerario che contengono rispettivamente aeroporti campione, compagnie aeree e rotte aeree. La raccolta di rotte collega gli aeroporti e le compagnie aeree come mostrato nella figura sottostante. Usiamo queste connessioni nel quickstart per generare aeroporti direttamente collegati e compagnie aeree che collegano un aeroporto di destinazione. Nota che questi sono solo esempi per evidenziare come è possibile utilizzare le query SQL++ per aggregare le collezioni.

Proviamo a rivedere il codice
Per iniziare questo tutorial, clonate il repo e apriamolo nell'IDE di vostra scelta. Ora potete imparare come creare, leggere, aggiornare e cancellare documenti in Couchbase Server.
Layout del codice
├── src
│ ├── Couchbase.TravelSample
│ │ ├── Models
│ │ │ ├── Airline.cs
│ │ │ ├── Airport.cs
│ │ │ └── Route.cs
│ │ ├── Properties
│ │ │ └── launchSettings.json
│ │ ├── Couchbase.TravelSample.csproj
│ │ ├── Program.cs
│ │ └── appsettings.Development.json
│ └── Couchbase.TravelSample.Tests
│ ├── AirlineTests.cs
│ ├── AirportTests.cs
│ ├── RouteTests.cs
│ ├── GlobalUsings.cs
│ └── Couchbase.TravelSample.Tests.csproj
├── Couchbase.TravelSample.sln
└── Dockerfile
We register the validators for the AirportCreateRequestCommand, AirlineCreateRequestCommand, e RouteCreateRequestCommand classes.
builder.Services.AddValidatorsFromAssemblyContaining(typeof(AirportCreateRequestCommandValidator));
In order to use the Couchbase.Extensions.DependencyInjection framework, we must first register the service. The Couchbase Services requires the database configuration information, which can be provided by reading the database configuration from the appsettings.Development.json file.
// Register the configuration for Couchbase and Dependency Injection Framework
builder.Services.Configure<CouchbaseConfig>(config);
builder.Services.AddCouchbase(config);
We initialise the bucket and scope during the application startup.
We check if the inventario scope exists in the provided Travel-sample bucket when the application starts and throw and exception if the inventario scope does not exist inside the Travel-sample bucket. We also log the Swagger URL here.
// Get the logger
var logger = app.Services.GetRequiredService<ILogger<Program>>();
// Get the address
var address = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault();
// Log the Swagger URL
logger.LogInformation("Swagger UI is available at: {Address}/swagger/index.html", address);
var configuration = builder.Configuration;
// Retrieve configuration values from appsettings.json
var bucketName = configuration["Couchbase:BucketName"];
var scopeName = configuration["Couchbase:ScopeName"];
if (string.IsNullOrEmpty(bucketName))
{
throw new InvalidOperationException("Bucket name is not provided in the configuration.");
}
if (string.IsNullOrEmpty(scopeName))
{
throw new InvalidOperationException("Scope name is not provided in the configuration.");
}
IBucket bucket;
try
{
bucket = app.Services.GetRequiredService<IBucketProvider>().GetBucketAsync(bucketName).GetAwaiter().GetResult();
}
catch (Exception)
{
throw new InvalidOperationException("Ensure that you have the travel-sample bucket loaded in the cluster.");
}
var scopes = bucket.Collections.GetAllScopesAsync().GetAwaiter().GetResult();
if (!(scopes.Any(s => s.Name == scopeName)))
{
throw new InvalidOperationException("Inventory scope does not exist in the bucket. Ensure that you have the inventory scope in your travel-sample bucket.");
}
inventoryScope = bucket.ScopeAsync(scopeName).GetAwaiter().GetResult();
The Couchbase SDK provides the ICouchbaseLifetimeService interface for handling closing the database connections when the application closes. It’s best practice to register for the ASP.NET ApplicationStop lifetime event and call the ICouchbaseLifetimeService Close method so that the database connection and resources are closed and removed gracefully.
//remove couchbase from memory when ASP.NET closes
app.Lifetime.ApplicationStopped.Register(() =>
{
var cls = app.Services.GetRequiredService<ICouchbaseLifetimeService>();
cls.Close();
});
The Couchbase .NET SDK will handle all communications to the database cluster, so you shouldn’t need to worry about creating a pool of connections.
Entità aeroportuale
For this tutorial, we will focus on the airport entity. The other entities are similar.
Stabiliremo un'API REST per gestire i documenti aeroportuali.
- Aeroporto POST – Creare un nuovo aeroporto
- GET Airport – Leggere l'aeroporto specificato
- Aeroporto di PUT – Aggiornamento aeroporto specificato
- DELETE Airport – Eliminare l'aeroporto
- Elenco degli aeroporti – Raccogliere tutti gli aeroporti. Opzionalmente è possibile filtrare l’elenco per paese
- Connessioni dirette – Ottieni una lista di aeroporti direttamente collegati all'aeroporto specificato
Per le operazioni CRUD utilizzeremo il Operazioni chiave-valore che sono integrate nel Couchbase SDK per creare, leggere, aggiornare e cancellare un documento. Ogni documento avrà bisogno di un ID (simile a una chiave primaria in altre database) per essere salvato nel database. Questo ID viene passato nell'URL. Per gli altri endpoint, utilizzeremo SQL++ per richiedere documenti.
Struttura dei documenti dell'aeroporto
Our airport document will have an airportname, city, country, faa code, icao code, timezone info and the geographic coordinates. For this demo, we will store all airport information in one document in the aeroporto raccolta nel Travel-sample bucket.
{
"airportname": "Sample Airport",
"city": "Sample City",
"country": "United Kingdom",
"faa": "SAA",
"icao": "SAAA",
"tz": "Europe/Paris",
"geo": {
"lat": 48.864716,
"lon": 2.349014,
"alt": 92
}
}
Aeroporto POST
Apri program.cs apri il file e naviga fino alla app.MapPost method for aeroporto collection.
It first validates the incoming request and if it’s not valid, it returns a validation problem.
If the inventoryScope is not null, it gets a reference to the collection where documents are stored, creates a new Airport object from the request, and attempts to insert the airport document into the database asynchronously using the InsertAsync method of the SDK.
If the insertion is successful, it returns a link to the GET API for the newly created document. If a document with the same id already exists, it returns a conflict result. For any other exceptions, it returns a problem with the exception message.
If the inventoryScope is null, it returns a problem stating “Scope not found”.
app.MapPost("/api/v1/airport/{id}", async (string id, AirportCreateRequestCommand request, IValidator<AirportCreateRequestCommand> validator) =>
{
var validation = await validator.ValidateAsync(request);
if (!validation.IsValid)
{
return Results.ValidationProblem(validation.ToDictionary());
}
try
{
if (inventoryScope is not null)
{
//get the collection
var collection = inventoryScope.Collection(airportCollection);
//get airport from request
var airport = request.GetAirport();
// Attempt to insert the document
await collection.InsertAsync(id, airport);
return Results.Created($"/api/v1/airport/{id}", airport);
}
else
{
return Results.Problem("Scope not found");
}
}
catch (DocumentExistsException)
{
// If a document with the same ID already exists, an exception will be thrown
return Results.Conflict($"A document with the ID '{id}' already exists.");
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
});
GET Airport
Apri program.cs apri il file e naviga fino alla app.MapGet method for aeroporto collection.
The function checks if the inventoryScope is not null, and if it is, it returns a problem stating “Scope Not Found”.
If the inventoryScope is not null, it gets a reference to the collection where documents are stored and retrieves the document from the database using GetAsync method of the SDK.
It then checks if a document was returned from the database. If a document was returned, it returns the document. If a document with the provided id does not exist in the database, it returns a NotFound result.
If any other exception occurs during the process, it returns a problem with the exception message.
app.MapGet("/api/v1/airport/{id}", async (string id) =>
{
try
{
if (inventoryScope is not null)
{
//get the collection
var collection = inventoryScope.Collection(airportCollection);
//get the document from the bucket using the id
var result = await collection.GetAsync(id);
//validate we have a document
var resultAirports = result.ContentAs<Airport>();
if (resultAirports != null)
{
return Results.Ok(resultAirports);
}
}
else
{
return Results.Problem("Scope not found");
}
}
catch (DocumentNotFoundException)
{
Results.NotFound();
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
return Results.NotFound();
});
Aeroporto di PUT
Apri program.cs apri il file e naviga fino alla app.MapPut method for aeroporto collection.
The method in the provided code is designed to update an airport record. The process begins with the validation of the incoming request using a provided validator.
If the request fails validation, a validation problem is returned with the associated errors.
If the request passes validation, the method checks for the existence of inventoryScope. If inventoryScope is null, it signifies that the scope was not found and a problem is returned. If inventoryScope exists, the airport collection is retrieved.
The method then attempts to fetch the current airport record from the database using the provided id.
If the airport record is found, it is updated with the new data using the ReplaceAsync method of the SDK and then updated record is returned.
If the airport record is not found, a 404 Not Found error is returned.
The method is also designed to handle exceptions. If any exceptions occur during the process, such as a Errore DocumentNotFound, the exception is caught and a problem with the exception message is returned.
app.MapPut("/api/v1/airport/{id}", async (string id, AirportCreateRequestCommand request, IValidator<AirportCreateRequestCommand> validator) =>
{
var validation = await validator.ValidateAsync(request);
if (!validation.IsValid)
{
return Results.ValidationProblem(validation.ToDictionary());
}
try
{
if (inventoryScope is not null)
{
//get the collection
var collection = inventoryScope.Collection(airportCollection);
//get current airport from the database and update it
if (await collection.GetAsync(id) is { } result)
{
result.ContentAs<Airport>();
await collection.ReplaceAsync(id, request.GetAirport());
return Results.Ok(request);
}
else
{
return Results.NotFound();
}
}
else
{
return Results.Problem("Scope not found");
}
}
catch (DocumentNotFoundException)
{
Results.NotFound();
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
return Results.NotFound();
});
DELETE Airport
Apri program.cs apri il file e naviga fino alla app.MapDelete method for aeroporto collection.
The method in the provided code is designed to delete an airport record. The process begins by checking for the existence of inventoryScope.
If inventoryScope is null, it signifies that the scope was not found and a problem is returned. If inventoryScope exists, the airport collection is retrieved.
The method then attempts to fetch the current airport record from the database using the provided id. If the airport record is found, it is deleted from the collection using the RemoveAsync method of the SDK and the id of the deleted record is returned.
If the airport record is not found, a 404 Not Found error is returned. The method is also designed to handle exceptions. If any exceptions occur during the process, such as a Errore DocumentNotFound, the exception is caught and a problem with the exception message is returned.
app.MapDelete("/api/v1/airport/{id}", async(string id) =>
{
try
{
if (inventoryScope is not null)
{
//get the collection
var collection = inventoryScope.Collection(airportCollection);
//get the document from the bucket using the id
var result = await collection.GetAsync(id);
//validate we have a document
var resultAirport = result.ContentAs<Airport>();
if (resultAirport != null)
{
await collection.RemoveAsync(id);
return Results.Ok(id);
}
else
{
return Results.NotFound();
}
}
else
{
return Results.Problem("Scope not found");
}
}
catch (DocumentNotFoundException)
{
Results.NotFound();
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
return Results.NotFound();
});
Lista aeroporti
Questo endpoint recupera l'elenco degli aeroporti presenti nel database. L'API offre la possibilità di specificare la dimensione della pagina dei risultati e il paese da cui estrarre i documenti relativi agli aeroporti.
SQL++ is a powerful query language based on SQL, but designed for structured and flexible JSON documents. We will use a SQL+ query to search for airports with Limit, Offset, and Country option.
Apri program.cs apri il file e naviga fino alla app.MapGet method for aeroporto collection. This endpoint is different from the others we have seen before because it makes the SQL++ query rather than a key-value operation. This usually means more overhead because the query engine is involved. For this query, we are using the predefined indices in the Travel-sample bucket. Possiamo creare un altro indice specifico per questa query per renderla più efficiente.
We need to get the values from the query string for country, limit, and Offset that we will use in our query. These are pulled from the queryParameters.Parameter.
Questo endpoint ha due query a seconda del valore del parametro Paese. Se viene specificato un nome di paese, recuperiamo i documenti relativi all’aeroporto per quel paese specifico. Se non viene specificato, recuperiamo l’elenco degli aeroporti di tutti i paesi. Le query sono leggermente diverse per questi due scenari.
Costruiamo la nostra query SQL++ utilizzando il parametri specificato da $ simbolo per entrambi questi scenari. La differenza tra le due query è la presenza del paese Il parametro nella query. Normalmente, per le query con la funzione di paginaazione, si consiglia di ordinare i risultati per mantenere l'ordine dei risultati in più query.
Successivamente passiamo oltre richiesta to the QueryAsync metodo. Salviamo i risultati in una lista, items.
This endpoint calls the QueryAsync metodo definito nel Ambito di applicazione tramite il SDK di Couchbase.
app.MapGet("/api/v1/airline/list", async (string? country, int? limit, int? offset) =>
{
try
{
if (inventoryScope is not null)
{
// setup parameters
var queryParameters = new Couchbase.Query.QueryOptions();
queryParameters.Parameter("limit", limit ?? 10);
queryParameters.Parameter("offset", offset ?? 0);
string query;
if (!string.IsNullOrEmpty(country))
{
query = $@"SELECT airline.callsign,
airline.country,
airline.iata,
airline.icao,
airline.name
FROM airline AS airline
WHERE lower(airline.country) = $country
ORDER BY airline.name
LIMIT $limit
OFFSET $offset";
queryParameters.Parameter("country", country.ToLower());
}
else
{
query = $@"SELECT airline.callsign,
airline.country,
airline.iata,
airline.icao,
airline.name
FROM airline AS airline
ORDER BY airline.name
LIMIT $limit
OFFSET $offset";
}
var results = await inventoryScope.QueryAsync<Airline>(query, queryParameters);
var items = await results.Rows.ToListAsync();
return items.Count == 0 ? Results.NotFound() : Results.Ok(items);
}
else
{
return Results.Problem("Scope not found");
}
}
catch (Exception ex)
{
return Results.Problem(ex.Message);
}
})
Connessioni dirette
This endpoint fetches the airports that can be reached directly from the specified source airport code. This also uses a SQL++ query to fetch the results similar to the List Airport endpoint.
Consideriamo la query utilizzata qui:
SELECT distinct (route.destinationairport)
DALLA STAZIONE AEROPORTUALE COME STAZIONE AEROPORTUALE
Inserire la rotta come percorso su route.sourceairport = airport.faa
WHERE $airport.faa = aeroporto e route.stops = 0
Ordine per percorso. Aeroporto di destinazione
LIMIT $limite
OFFSET $offset
Raccogliamo le connessioni dirette unendo la raccolta dell'aeroporto alla raccolta del percorso e filtrando in base all'aeroporto di origine specificato dall'utente e alle rotte senza fermate.
Running The Tests
We have defined integration tests using the xunit nuget package for all the API end points. The integration tests use the same database configuration as the application. For the integration tests, we perform the operation using the API and confirm the results by checking the documents in the database. For example, to check the creation of the document by the API, we would call the API to create the document and then read the same document from the database and compare them. After the tests, the documents are cleaned up by calling the DELETE endpoint
To run the standard integration tests, use the following commands:
cd ../Couchbase.TravelSample.Tests/
dotnet restore
dotnet build
dotnet test
Appendice
Ampliare l'API aggiungendo un'entità nuova
Se desiderate aggiungere un'altra entità alle API, i passaggi da seguire sono i seguenti:
- Creare la nuova entità (collezione) nel bucket Couchbase. È possibile creare la collezione utilizzando il comando SDK o tramite il Interfaccia del server Couchbase.
- Define the routes in
program.csfile similar to the existing routes. - Aggiungere i test per le nuove rotte in un nuovo file nel
Couchbase.TravelSample.Testsuna cartella simile aAirportTests.cs.
Gestione automatica di un cluster di Couchbase
Se stai eseguendo questo quickstart con un cluster di Couchbase gestito autonomamente, è necessario caricare caricare i dati del bucket dei dati di viaggio nel cluster e generare le credenziali per il bucket.
È necessario aggiornare la stringa di connessione e le credenziali nel file appsettings.Development.json file nella cartella di origine.
NOTA: Couchbase must be installed and running prior to running the the ASP.NET app.
Documentazione Swagger
La documentazione di Swagger fornisce una panoramica chiara dell'API, includendo endpoint, metodi HTTP, parametri delle richieste e oggetti di risposta.
Fare clic su un singolo endpoint per ampliarlo e visualizzare le informazioni dettagliate. Ciò include la descrizione dell’endpoint, i possibili codici di stato delle risposte e i parametri della richiesta che esso accetta.
Testare l'API
È possibile provare un'API cliccando sul pulsante “Prova” accanto agli endpoint.
-
Parametri: Se un endpoint richiede parametri, l'interfaccia utente Swagger fornisce dei campi di input da compilare. Questi possono includere parametri di percorso, stringhe di query, intestazioni o il corpo di una richiesta POST/PUT.
-
Esecuzione: Una volta inseriti tutti i parametri necessari, è possibile cliccare sul pulsante “Esecuzione” per effettuare una chiamata API in tempo reale. L’interfaccia utente Swagger invierà la richiesta all’API e visualizzerà la risposta direttamente nella documentazione. Ciò include il codice della risposta, gli header e il corpo della risposta.
Modelli
Swagger documenta la struttura dei corpi di richiesta e risposta utilizzando modelli. Questi modelli definiscono la struttura dei dati prevista utilizzando lo schema JSON e sono estremamente utili per comprendere quali dati inviare e quali aspettarsi.