Skip to content

Instantly share code, notes, and snippets.

@rchacon
Created August 18, 2014 20:55
Show Gist options
  • Save rchacon/edd455a8eceabe40af15 to your computer and use it in GitHub Desktop.
Save rchacon/edd455a8eceabe40af15 to your computer and use it in GitHub Desktop.
REST API Example built with ASP.NET MVC 4
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace api_v1_csharp.Models.academics
{
public class Program
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
public bool isThinkpad { get; set; }
public string shortName { get; set; }
public bool isNorwich { get; set; }
public int year { get; set; }
public int schoolId { get; set; }
public bool isHidden { get; set; }
public string requirements { get; set; }
public string imgPath { get; set; }
public string programChair { get; set; }
public string folder { get; set; }
public string thumbImgPath { get; set; }
// navigation property
public School school { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace api_v1_csharp.Models.academics
{
public class ProgramsRepository : IProgramsRepository
{
private AcademicsDbContext db = new AcademicsDbContext();
public Program GetProgram(int id)
{
try
{
Program program = db.Programs.Include("school").Single(p => p.id == id);
return program;
}
catch (Exception ex)
{
return null;
}
}
public IEnumerable<Program> GetPrograms()
{
IQueryable<Program> programs =
from p in db.Programs.Include("school")
select p;
return programs.Any() ? programs : null;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using api_v1_csharp.Models.academics;
namespace api_v1_csharp.Controllers
{
public class ProgramsController : ApiController
{
static readonly IProgramsRepository _repository = new ProgramsRepository();
// GET v1/programs/{ id }
public HttpResponseMessage Get(int id)
{
Program program = _repository.GetProgram(id);
if (program == null)
{
var message = string.Format("Program with id = {0} not found", id);
HttpError err = new HttpError(message);
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, program);
}
}
// GET /v1/programs
public HttpResponseMessage GetPrograms()
{
IEnumerable<Program> programs = _repository.GetPrograms();
if (programs == null)
{
var message = string.Format("Programs not found");
HttpError err = new HttpError(message);
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, programs);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment