Home > Software engineering >  RESTFul API Get method with both FromRouteAttribute and FromQuery
RESTFul API Get method with both FromRouteAttribute and FromQuery

Time:10-03

I have an existing RESTFul API that has the below endpoints implemented already.

[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
    [HttpGet]
    public Items Get()
    {
         return new Items();
    }

    [HttpGet("{id}")]
    public Item Get(Guid id)
    {
        var item = new Item(id);
        return item;
    }
}

Above endpoints work for below Url,

GET /Items

GET /Items/{id}

Now I want to add a new endpoint that should work for the below URL,

GET /Items?name={name}

I have tried few ways but I couldn't get that work, Could you please help me with this.

Thank you all.

CodePudding user response:

you can do this:

public class MyClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}


[ApiController]
[Route("[controller]")]
public class NamesController : ControllerBase
{
    private readonly List<MyClass> myClasses;

    public NamesController()
    {
        myClasses = new List<MyClass>
        {
            new MyClass{Id=1,Name="Sara"},
            new MyClass{Id=2,Name="Nina"},
            new MyClass{Id=3,Name="John"},
        };
    }
 
    
    // https://localhost/names
    // https://localhost/names?name="Sara"
    [HttpGet]
    public IActionResult GetAll(string name)
    {

        if (!string.IsNullOrWhiteSpace(name))
            return Ok(myClasses.FirstOrDefault(x => x.Name == name));
        else
            return Ok(myClasses);
    }


    // https://localhost/names/1
    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {

        var item = myClasses.FirstOrDefault(x => x.Id == id);
        return Ok(item);
    }
}
  • Related