* You have so far implemented GET and POST methods for reading resources from the API and creating new ones to it
<!-- headingDivider: 5 -->
* All the primary methods for following the uniform interface requirement are __GET, POST, PUT, PATCH __ and __DELETE__
<!-- class: invert -->
## Contents
- [HTTP methods for RESTful APIs](#http-methods-for-restful-apis)
- [HTTP `POST` method](#http-post-method)
- [HTTP `PUT` method](#http-put-method)
- [HTTP `DELETE` method](#http-delete-method)
- [HTTP `PATCH` method](#http-patch-method)
## HTTP methods for RESTful APIs
### RESTful API
* We'll be extending our Web API into a full-blown ***RESTful API***
* More about REST in [Frontend Basics Lecture 3: REST Architecture](https://gitea.buutti.com/education/frontend-basics/src/branch/main/3-rest-architecture.md)
* A good idea to also check out [Frontend Basics Lecture 2: HTTP methods](https://gitea.buutti.com/education/frontend-basics/src/branch/main/2-http.md)
* We have so far implemented `GET` and `POST` methods for reading resources from the API and creating new ones to it, respectively
* All the primary methods for following the uniform interface requirement are `GET`, `POST`, `PUT`, `PATCH` and `DELETE`
* Others exist, but these are by far most commonly used
* Others exist, but these are by far most commonly used
* These methods correspond to __CRUD __ operations __Create__ , __Read__ , __Update __ and __Delete__
* These methods correspond to ***CRUD*** operations *__Create__*, *__Read__*, *__Update__* and *__Delete__*
* CRUD describes what is done to a resource after a request is sent
* CRUD describes what is done to a resource after a request is sent
# HTTP Methods for RESTful APIs (continued)
### Primary HTTP request methods
The primary HTTP request methods with descriptions:
The primary HTTP request methods with descriptions:
Remember, that HTTP requests can include a content body
### Handling `HttpPost` Requests
In ASP.NET, this content is assigned to a variable with the [FromBody] attribute:
* Remember that HTTP requests can include a content body
* In ASP.NET, this content is assigned to a variable with the `[FromBody]` attribute:
```csharp
[HttpPost]
[HttpPost]
public string[] Post([FromBody] string someContent)
public string[] Post([FromBody] string someContent)
{
{
// someContent holds the content of the request body
// someContent holds the content of the request body
return new string[] { text };
return new string[] { text };
}
}
```
* Note that the `[FromBody]` attribute can only be used on one parameter
* However, nothing prevents you from using a custom type variable
Note that the [FromBody] attribute can only be used on one parameter
---
However, nothing prevents you from using a custom type variable
# Handling HttpPost Requests (continued)
ASP.NET deserializes the request content body into an object:
public class Student
* ASP.NET deserializes the request content body into an object:
```csharp
// Models/Contact.cs
public class Contact
{
{
public int Id { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Name { get; set; }
}
}
```
// In controller class:
* ```csharp
// Controllers/ContactsController.cs
[HttpPost]
[HttpPost]
public Contact Put(int id, [FromBody] Contact contact)
public Contact Put(int id, [FromBody] Contact contact)
{
{
// Contacts is a list of Contact objects, fetched from some repository
// Contacts = list of Contact objects, fetched from some repository
Contacts.Add(contact);
Contacts.Add(contact);
return contact;
return contact;
}
}
```
### Creating a POST Request with Postman
# Creating a POST Request with Postman
#### Request headers
* ASP.NET knows to deserialize the content if the content type is set to JSON in the HTTP requests __headers__
* ASP.NET knows to deserialize the content if the content type is set to JSON in the HTTP requests *__headers__*
* Headers are optional parameters that can be included in every HTTP request
* Headers are optional parameters that can be included in every HTTP request
* Headers are set in Key-Value format
* Headers are set in a Key-Value format
* When creating a request in Postman, to inform the server what type of content was just sent, add a new key "Content-Type" and set its value to "application/json" in the _Headers _ tab:
* When creating a request in Postman, to inform the server what type of content was just sent, add a new key `Content-Type` and set its value to `application/json` in the _Headers_ tab:

<divclass='centered'>
# Creating a POST Request with Postman (continued)

After setting the header,
</div>
select the Body tab,
#### Request body
change the content type to raw,
After setting the header,
1) select the Body tab,
2) change the content type to raw,
3) select JSON from the dropdown menu, and
4) insert the content in JSON format
select JSON from the dropdown menu, and
<divclass='centered'>
insert the content in JSON format


</div>
# Creating a POST Request with Postman - Example
Suppose the Post method from before is routed at http://localhost:54106/api/students:
#### Sending the request

* If the `POST` method is routed at `http://localhost:54106/api/contacts`:
# Exercise 1: Creating a POST Endpoint
<divclass='centered'>
Continue working on CourseAPI.

Create a Post method and endpoint which adds a new course to the list in the repository, with a running ID. Content and Author values are obtained from the request body:
</div>

### Exercise 1: Creating a `POST` Endpoint
<!--_class: "exercise invert" -->
# HTTP PUT
Continue working on the CourseAPI.
Use PUT to replace an existing resource, e.g. an element in a list, with a new one
1) Create a `POST` method and endpoint which adds a new course to the list in the repository with a running ID. Content and Author values are obtained from the request body:

The ID of the resource to be replaced should be in the request URI
## HTTP `PUT` method
The information about the new resource should be in the request body like in POST requests
* Use `PUT` to replace an existing resource, e.g. an element in a list, with a new one
* The ID of the resource to be replaced should be in the request URI
* The information about the new resource should be in the request body like in `POST` requests

<divclass='centered'>
# Handling HttpPut Requests

The ID is fetched from the URI and the contents from the request body
</div>
Filtering is used to copy all objects from the original list except for the new contact object, which comes from body
### Handling `HttpPut` requests
* The ID is fetched from the URI and the contents from the request body
* Filtering is used to copy all objects from the original list except for the new `contact` object, which comes from body
```csharp
// Controllers/ContactsController.cs
[HttpPut("{id}")]
[HttpPut("{id}")]
public List<Contact> Put(int id, [FromBody] Contact contact)
public List<Contact> Put(int id, [FromBody] Contact contact)
{
{
// Contacts is a list of Contact objects, fetched from some repository
// Contacts = list of Contact objects, fetched from some repository
List<Contact> updatedList = Contacts.Select(c => c.Id != id ? c : contact).ToList();
List<Contact> updatedList = Contacts.Select(c => c.Id != id ? c : contact).ToList();
Contacts = updatedList;
Contacts = updatedList;
return updatedList;
return updatedList;
}
}
```
# Exercise 2: Creating a PUT Endpoint
### Exercise 2: Creating a `PUT` Endpoint
* In CoursesController class, create a method for PUT requests with the URI api/courses/{id}
* In CoursesController class, create a method for PUT requests with the URI api/courses/{id}
* The ID of the course to be replaced with should be in the request URI and the contents of the new course should be in the request body.
* The ID of the course to be replaced with should be in the request URI and the contents of the new course should be in the request body.
@ -152,105 +170,103 @@ return updatedList;
* Return a 404 status code if a course with the corresponding ID does not exist
* Return a 404 status code if a course with the corresponding ID does not exist
* Test with Swagger/Postman
* Test with Swagger/Postman
# HTTP DELETE
## HTTP `DELETE` method
Use DELETE to delete an existing resource, e.g. an element in a list
The ID of the resource to be deleted should be in the request URI
As with GET method, a body is not needed
* Use `DELETE` to delete an existing resource, e.g. an element in a list
* The ID of the resource to be deleted should be in the request URI
* As with the `GET` method, a body is not needed


# Handling HttpDelete Requests
### Handling `HttpDelete` Requests
The ID is fetched from the URI
* The ID is fetched from the URI
```csharp
// Controllers/ContactsController.cs
[HttpDelete("{id}")]
[HttpDelete("{id}")]
public List<Contact> Delete(int id)
public List<Contact> Delete(int id)
{
{
// Contacts = list of contact objects, fetched from some repository
// Contacts = list of contact objects, fetched from some repository
* Create an endpoint for DELETE requests with the URI api/courses/{id}
* The ID of the course should be fetched from the URI
* The corresponding course should be removed from the list of courses in the repository
* The method should return the updated Courses list (for testing purposes)
* Return a 404 status code if a course with the corresponding ID does not exist
* Test with Postman
# HTTP PATCH
* Use PATCH to partially update a resource
* I.e. update some value inside of a resource
* This saves some resources as only a part of a resource has to be sent instead of an entire document (as opposed to PUT requests)
* Sending and handling PATCH requests with ASP.NET requires some extra work and the use of a third party package: [http://jsonpatch.com/](http://jsonpatch.com/)
# HTTP PATCH (continued)
* To handle PATCH requests in a standardized way, install and add the following NuGet packages to your project:
* Microsoft.AspNetCore.JsonPatch
* Microsoft.AspNetCore.Mvc.NewtonsoftJson
* Then, change the following line in Program.cs (ASP.NET 5: Startup.cs)...