user3266638
user3266638

Reputation: 449

What should be returned from the Get request in the web API?

I am trying to return a list of objects that come from a database call that look like this:

public class ObjectA
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ObjectB ObjB { get; set; }
}

public class ObjectB
{
    public int Id { get; set; }
    public string Field { get; set; }
}

Call to get item from database in web api

    [HttpGet]
    public List<ObjectA> GetObjects([FromUri] int id)
    {
        var objs= objectRepo.All.Where(x => x.Id== id).ToList();
        return objs;
    }

Call from HTTPCLIENT

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri("http://localhost:2478/api/controller/");
var result= client.GetAsync("GetObjects?id=" + 5);

Is there a better way to set up the get method? And how would the returned results be used once retrieved using httpclient?

I don't need to object B as an object belonging to object A but I do need the field from object B.

Upvotes: 0

Views: 825

Answers (1)

meJustAndrew
meJustAndrew

Reputation: 6623

From the comments:

is it okay to return a list of objects like that?

If you have control over the API and if you just need the ObjectB from your ObjectA, then I would suggest you to change the API to return just ObjectBs or even just the Field from ObjectB. For example:

objectRepo.All.Where(x => x.Id == id).Select(x => x.ObjB).ToList();

which will return a list of ObjectBs.

should the parameter be passed into the Uri and not from the body if that's possible

Yes, it can be passed in the URI using [HttpGet("{id}")].

In the end you will have:

[HttpGet("{id}")]
public List<ObjectB> GetObjects(int id)
{
    return objectRepo.All.Where(x => x.Id == id).Select(x => x.ObjB).ToList();
}

Upvotes: 1

Related Questions