(C# ASP.NET Core) Minimal GET WebApi to Find a Record by Id

In this tutorial we shall add a web api of GET type that takes an ID as a parameter and returns a record for that parameter.
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

The URL for a GET Api that accepts parameters

Let us first decide on the URL of this API.

The URL has to contain a parameter called id. So we should use curly braces and append this parameter to the path like: /doctor/{id}


/doctor/{id}

Video Explanation (see it happen!)

Please watch the following youtube video:

Adding this API to Program.cs file

Next let us add this API to the Program.cs file!

Open the solution explorer. We are using this project (see the attached video) to learn web api.

With each tutorial we are adding a web api and testing it. Please refer the first tutorial of this chapter where we created this simple project. You can even find the source code for this and other tutorials in the attached downloads if you are following our course on ASPNET Core.

Double-click and open the program.cs file and scroll a few lines down to reach the part that are seeing here.

// program.cs 
// previous code not shown 
// for simplicity 
// or please check the attached downloads 

// find record by ID 
app.MapGet("/doctor/{id}",
    async (MyApiContext ctx, int id) =>
    {
        if (await ctx.FindAsync<Doctor> (id) is Doctor doctor)
        {
            return Results.Ok(doctor);

        }
        else
        {
            return Results.NotFound();

        }
    }
  );


// trailing code not shown for clarity 
// and simplicity 
// please check the attached downloads 
// if you are following our course on ASPNET Core 

MapGet function is used to add a web api. The first parameter is the route template. The second parameter is the function that executes when the API is called by a calling client. If the record can be found, then the record is sent with a 200 OK response. Notice that most of the work is being done by the ASPNET Core functions. We need to write only a few lines of code.

If there is no matching record then an HTTP 404 response is sent.

Run the Application

Finally, let us run the project!

Type the URL /doctor/1 for the record of id = 1. We verify that the server responds with a json formatted record of id = 1.

Everything is working correctly. Thanks!


This Blog Post/Article "(C# ASP.NET Core) Minimal GET WebApi to Find a Record by Id" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.