Prep RESTful API & Web Services

  1. What is a REST? Explain.
    Originally introduced in 2000, Representational State Transfer is an architectural pattern for creating lightweight web services using the Http protocol by exchanging data across the web, often between disjointed systems. As such, two different systems can communicate and exchange data...for example, a mobile app user in Ohio can view map data from a web API located on an Apple system in Beijing.
  2. Which is better to use, REST or SOAP? Why?
    REST is considered fast, lighter (less bandwidth); SOAP uses XML only, while REST allows JSON, XML, Raw, and more. SOAP has better security and more functionality; SOAP provides ACID compliant transactions and allows schema and some business processes to be seen. Which is better? It depends on the need, but typically, you can say that you use REST in all cases except those that have a specific requirement which SOAP meets because the additional overhead typically isn't necessary.
  3. Write a simple JSON object of a student containing name, dob, and sex.
    var obj = { "id": 1, "name": "Matthew", "dob": "01/10/1971", "isMale": true };
  4. What is the 5 Http verbs and how are they typically called in an API?
    • Verbs represent Get, Post, Put, and Delete; used to update or retrieve resources within an API.
    • api/Leads Get: get all leads
    • api/Lead/1 Get: a specific leads
    • api/Leads Post: Creates a new leads
    • api/Lead/1 Put: Updates employee
    • api/Lead/1 Delete: Deletes an employee
  5. What does it mean to say a RESTful Web API service is stateless?
    RESTful applications, like Http, is stateless in that every request of the API is self contained and has no "memory" of previous data values or calls.
  6. What are the 5 categories of Http status codes?
    • (1) 1xx - Informational, rarely used
    • (2) 2xx - Success, client sent a message, server accepted it
    • (3) 3xx - Redirection, server received and redirected request
    • (4) 4xx - Client error, perhaps the client sent a bad request and the server cannot continue until client fixes error
    • (5) 5xx - Server error, server received a good request but failed to perform the error for some reason.
  7. What are the most common Http status codes and their meaning?
    • 200: OK
    • 201: Created

    • 400: Bad Request (client side)
    • 401: Unauthorized (invalid credentials)
    • 403: Forbidden (authenticated, but no permissions)
    • 404: Not Found (item couldn't be found)

    • 500: Internal Server Error (server side)
    • 503: Service Unavailable
  8. What status codes and return results should be used on each CRUD method? Why are multiple code types important when returning a result?
    It's very important to return both the successful and unsuccessful messages to the user because of the API's lack of state management, since calling the exact same method with similar parameters can return multiple results. 

    An example of this is the call to DeleteBook(int id). The following 4 return values. 

    • (a) Id is 0, return 400 (bad request)
    • (b) Id is 3, but not in database, return 404 (not found)
    • (c) Id is 3, database error, return 500 or 400 (bad request)
    • (d) Id is 3, item deleted
  9. What's the difference between a protocol and an architecture? How does this relate to SOAP vs REST?
    RESTful web service API's isn't a protocol but an architectural style (method) of  communicating across Http using JSON, XML, URI's, HTTP and more. While it uses several different protocols to perform this exchange, it isn't a protocol like SOAP (Simple Object Access Protocol).

    A protocol is another word for a standard, so JSON, XML, HTTP, HTTPS, URI, and SOAP are all different standards/protocols whereas web services (APIs) aren't a standard but an architectural style (methodology) for communicating across the web.

    Architectural styles tend to be more scoped, less rigid, providing a framework for doing things ... the benefit of being more rigid for SOAP includes being more robust, can contain transaction information, can contain other protocols like https, encryption, and mail protocols, and SOAP is more secure, the downside is it isn't lightweight, fast, or as easy to work with as web services.
  10. Explain four high-level steps needed to create, run, and test simple REST web service using Visual Studio 2017.
    1. Visual Studio 2017 | New Project | C# Web | ASP.NET Web Application (.NET Framework) | Web API

    2. Right click Controller folder and choose Add | Controller | Choose Web API Controller

    3. Create the CRUD API methods needed and then run the application so that the API is viewable in the browser.

    4. Now use Postman or another application to attach to that service while it is running to test it.
  11. Show the browser call needed to call the GetName and GetName(id) api at localhost:13857.
    • http://localhost:13857/api/GetName
    • http://localhost:13857/api/GetName/2 
    • http://localhost:13857/api/GetName?id=3
  12. Write an async method to get all books using a list.
    • [HttpGet]
    • [Route("api/GetBooks")]
    • public async Task<IActionResult> GetBooks()
    • {
    •   List<Book> books = await _db.Books.ToListAsync();
    •   if (books == null)
    •     return NotFound("No books were found.");

    •   return Ok(books);
    • }
  13. Write an async method to a single book.
    • [HttpGet]
    • [Route("api/GetBook/{id}")]
    • public async Task<IActionResult> GetBook(int id)
    • {
    •   if (id == 0)
    •     return BadRequest(string.Format("The Id {0} value provided is invalid.", id));

    •   var book = await _db.Books.FindAsync(id);
    •   if (book == null)
    •     return NotFound(string.Format("Book Id {0} could not be found."));

    •   return Ok(book);
    • }
  14. Write an async method to add a new book.
    • [HttpPost]
    • [Route("api/PostBook")]
    • public async Task<IActionResult> PostBook([FromBody] Book book)
    • {
    •   if (!ModelState.IsValid)
    •      return BadRequest(ModelState);

    •   try
    •   {
    •      _db.Books.Add(book);
    •      await _db.SaveChangesAsync();
    •   }
    •   catch(Exception ex)
    •   {
    •      return BadRequest(ex.Message);
    •   }

    •   return Ok(book);
    • }
  15. Write an async method to update a book.
    • [HttpPost]
    • [Route("api/PutBook")]
    • public async Task<IActionResult> PutBook([FromBody] Book book)
    • {
    •   if (!ModelState.IsValid)
    •     return BadRequest(ModelState);

    •   if (book.Id <= 0)
    •     return BadRequest(string.Format("Book Id {0} is invalid."));

    •   try
    •   {
    •     _db.Update(book);
    •     await _db.SaveChangesAsync();
    •   }
    •   catch(DbUpdateException ex)
    •   {
    •     return BadRequest(ex.Message);
    •   }

    •   return Ok(book);
    • }
  16. Write an async method to delete a book.
    • [HttpDelete]
    • [Route("api/DeleteBook/{id}")]
    • public async Task<IActionResult> DeleteBook(int id)
    • {
    •   if (id == 0)
    •     return BadRequest(string.Format("The Id {0} value provided is invalid.", id));

    •   var book = await _db.Books.FindAsync(id);
    •   if (book == null)
    •     return NotFound(string.Format("Book Id {0} could not be found."));

    •   try
    •   {
    •   _db.Remove(book);
    •   await _db.SaveChangesAsync();
    •   }
    •   catch(DbUpdateException ex)
    •   {
    •     return BadRequest(string.Format("Book Id {0} could not be deleted [" + ex.Message + "].", id));
    •   }
    •   return Ok();
    • }
  17. What headers can be used above the CRUD API method calls?
    • (a) Prefix, like [Prefix('api/SomeController')]
    • (b) Routing, like [Route('api/GetBook/{id}')]
    • (c) Http verbs such as HttpGet, HttpPost
  18. Explain how objects and simple data types are sent to the API methods.
    Simple data types (ie, integer, date, string, bool, etc) are passed using the Uri itself. However, complex types such as Model, ViewModel, and others can only be passed in the body of the request and usually through Json or XML.

    It's important to remember that while numerous simple types may be passed through the Uri, only one object can be passed through, so if two different objects need to be updated, they must be combined together in a ViewModel.
  19. Write a full ProductController and include a Product class and database connection class.
    • [RoutePrefix('api/Model')]
    • public class ProductController: ApiController
    • {
    • private DataContext _db = new DataContext();

    • private
    • [HttpGet]
    • [Route('Get')]
    • public async Task<IEnumerable<model> Get();

    • [HttpGet]
    • [Route('/Get/{id}')]
    • public async Task<IHttpActionResult> Get([FromUri] id);

    • [HttpPost]
    • [Route('/Post')]
    • public async Task<IHttpActionResult> Post([FromBody] model);

    • [HttpPut]
    • [Route('/Put/{id}')]
    • public async Task<IHttpActionResult> Put([FromUri] id, [FromBody] model);

    • [HttpDelete]
    • [Route('/Delete/{id}')]
    • public async Task<IHttpActionResult> Delete([FromUri] id);
    • }

    • public class DataContext: DbContext
    • {
    • public DbSet<Product> Products { get; set; }
    • public DbSet<Movie> Movies { get; set; }
    • public DbSet<Model> Models { get; set; }
    • }

    • public class Products
    • {
    • public int Id { get; set; }
    • public string Name { get; set; }
    • public decimal Price { get; set; }
    • public int UnitsInStock { get; set; }
    • }
  20. We often use IActionResult as the return type from a web service? Why?
    IActionResult is an interface whereas ActionResult is one of many implementations of that interface. The other implementations to return data to the calling procedure include:

    • (a) ActionResult
    • (b) EmptyResult
    • (c) FileResult
    • (d) ContentResult
    • (e) HttpStatusCodeResult
    • (f) JavaScriptResult
    • (g) JsonResult
    • (h) RedirectResult
    • (i) RedirectToRouteResult

    As with most things, you probably aren't going to use IActionResult itself, but will use one of its implementation later in the view or elsewhere, such as returning a Json object for use with angular or JavaScript.
Author
mateotete
ID
342131
Card Set
Prep RESTful API & Web Services
Description
RESTful web service API cards.
Updated