In my previous post I setup a simple Azure function to update data in Cosmos DB. This post will review the simple code to retrieve trip entries by id using an Azure function. The next version of the project adds another Azure function for handling GET requests with the tripId on the end of the url.
Get Trigger/Binding
The GetTripRequest Azure function in the TripLoggerServices project supports retrieving a trip from Cosmos DB by the id passed on the url. The function uses the HttpTrigger attribute to trigger the function from an HTTP GET request that uses the proper route of ‘trips/{tripId}’. The CosmosDB attribute is used to look up the trip entry in Cosmos DB based on the tripId on the url.
public static class GetTripRequest
{
[FunctionName("GetTripRequest")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "trips/{tripId}")] HttpRequest req,
string tripId,
[CosmosDB(
databaseName: "TripLog",
collectionName: "Trips",
CreateIfNotExists = true,
Id = "{tripId}",
ConnectionStringSetting = "CosmosDBConnection")]TripEntry tripEntry,
ILogger log)
{
}
}
HttpTrigger
The HttpTrigger attribute is configured to bind the HttpRequest to the req function parameter (line 5) and the route parameter “trips/{tripId}” to the string tripId function parameter (line 6). Note that the ‘req’ parameter isn’t used but it is still bound. The binding is configured to only respond to GET request by passing “get” to the methods attribute parameter.
Cosmos Input Binding
To retrieve the record from Cosmos DB by Id the Id=”{tripId}” parameter of the CosmosDB attribute is used. By setting the value to a template string the attribute knows to use the value for the tripId set by the HttpTrigger (line 11). If the trip entry is found in Cosmos DB the tripEntry parameter will contain the retrieved record. If the trip entry is not found the tripEntry parameter will be null.
Processing the Request
The processing for the GET request is very simple. If the entry isn’t found return a 404 otherwise return the entry.
if (tripEntry == null)
{
return new NotFoundObjectResult($"Could not find trip entry with id: {tripId}");
}
return new OkObjectResult(tripEntry);
First the tripEntry is checked for null, if the parameter is null we know that the entity was not found in CosmosDB and return a 404 response (lines 1-4). Otherwise an 200 OK response is sent (line 6) with the tripEntry object for the result object.
With the addition of the GetTripRequest Azure function it is now possible to get previously logged trip by id in CosmosDB.