0% found this document useful (0 votes)
236 views12 pages

Corer 2.2

The document describes an ASP.NET Core REST API tutorial that covers setting up and configuring Swagger, implementing versioning, dependency injection, and creating, retrieving, updating and deleting resources. It includes code examples for setting up the API project structure, controllers, services, models and routes. Key steps covered are configuring Swagger UI, creating API versions, registering services via dependency injection, and building CRUD operations for a post resource.

Uploaded by

samer_mf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
236 views12 pages

Corer 2.2

The document describes an ASP.NET Core REST API tutorial that covers setting up and configuring Swagger, implementing versioning, dependency injection, and creating, retrieving, updating and deleting resources. It includes code examples for setting up the API project structure, controllers, services, models and routes. Key steps covered are configuring Swagger UI, creating API versions, registering services via dependency injection, and building CRUD operations for a post resource.

Uploaded by

samer_mf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] CORE 2.

2 & 3 REST API TUTORIAL

HTTPS://[Link]/PLAYLIST?LIST=PL UOEQUMGNXXOGMSDWU7TL 6IQTSOTYJTWU

TABLE OF CONTENTS
[Link] ........................................... 1
[Link] Core 2.2 REST API Tutorial 1 - Setup and Swagger configuration ................................................................... 2
[Link] Core 2.2 REST API Tutorial 2 - Implementing versioning................................................................................. 4
[Link] Core 2.2 REST API Tutorial 3 - Dependency injection and clean service registration ..................................... 5
[Link] Core 3 & 2.2 REST API Tutorial 4 - Creating resources using POST ................................................................. 7
[Link] Core 3 & 2.2 REST API Tutorial 5 - Retrieving resources with GET .................................................................. 8
[Link] Core 2.2 REST API Tutorial 6 - Updating resources with PUT ........................................................................ 11
[Link] Core 3 & 2.2 REST API Tutorial 7 - Deleting resources with DELETE ............................................................. 12
[Link] CORE 2.2 REST API TUTORIAL 1 - SETUP AND SWAGGER CONFIGURATION

Delete IIS express from properties

Add swagger [Link] RE


Add folder Options, create class [Link]
public class SwaggerOptions
{

public string JsonRoute { get; set; }


public string Description { get; set; }
public string UiEndpoint { get; set; }
}

Add to startup the following code


var swaggerOptions = new SwaggerOptions();
[Link](nameof(SwaggerOptions)).Bind(swaggerOptions);

[Link](option => { [Link] = [Link]; });


[Link](option =>
{
[Link]([Link], [Link]);
});
[Link] CORE 2.2 REST API TUTORIAL 2 - IMPLEMENTING VERSIONING

Create folder Domain, create class [Link]

public class Post


{
public string Id { get; set; }
}

Create Controllers/api/v1, create class [Link]

public class PostsController : Controller


{
private List<Post> _posts;

public PostsController()
{
_posts = new List<Post>();
for (var i = 0; i < 5; i++)
{
_posts.Add(new Post{Id = [Link]().ToString()});
}
}

[HttpGet([Link])]
public IActionResult GetAll()
{
return Ok(_posts);
}

Create folder Contract, create class Contract/v1/[Link]

public static class ApiRoutes


{
public const string Root = "api";
public const string Version = "v1";
public const string Base = Root + "/" + Version;

public static class Posts


{
public const string GetAll = Base+"/posts";
public const string Create = Base + "/posts";
public const string Get = Base + "/posts/{postId}";

}
}
[Link] CORE 2.2 REST API TUTORIAL 3 - DEPENDENCY INJECTION AND CLEAN SERVICE
REGISTRATION

Create folder Installers, create interface [Link]


public interface IInstaller
{
void InstallServices(IServiceCollection services , IConfiguration configuration);

Create class [Link] which implements IInstaller interface


public class MvcInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
[Link]<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
[Link]<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given
request.
[Link] = context => true;
[Link] = [Link];
});

[Link]().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
[Link](x =>
{
[Link]("v1", new Info { Title = "Tweetbook API", Version = "v1" });
});
}
}

Create class [Link] which implements IInstaller interface


public class DbInstaller :IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
[Link]<ApplicationDbContext>(options =>
[Link](
[Link]("DefaultConnection")));
}
}
Create class [Link]
public static class InstallerExtensions
{
public static void InstallServicesInAssemble(this IServiceCollection services, IConfiguration
configuration)
{
var installers = typeof(Startup).[Link](x =>
typeof(IInstaller).IsAssignableFrom(x) && ![Link] &&
![Link]).Select([Link]).Cast<IInstaller>().ToList();
[Link](installer => [Link](services, configuration));

Remove from method ConfigureService from [Link] and make it:


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
[Link](Configuration);
}
[Link] CORE 3 & 2.2 REST API TUTORIAL 4 - CREATING RESOURCES USING POST

Create new folders Contract/v1/Requests and Contract/v1/Responses

Create new class Contract/v1/Requests/[Link]


public class CreatePostRequest
{
public string Id { get; set; }
}

Create new class Contract/v1/Responses/[Link]


public class PostResponse
{
public string Id { get; set; }
}

Add new method to [Link]


[HttpPost([Link])]
public IActionResult Create([FromBody] CreatePostRequest postRequest)
{
var post = new Post{Id=[Link]};

if ([Link]([Link]))
[Link] = [Link]().ToString();

_posts.Add(post);

var baseUrl = $"{[Link]}://{[Link]()}";


var locationUri = baseUrl + "/" + [Link]("{postId}", [Link]);
var response = new PostResponse {Id = [Link]};
return Created(locationUri, response);
}
[Link] CORE 3 & 2.2 REST API TUTORIAL 5 - RETRIEVING RESOURCES WITH GET

Modify [Link], add string name, and make Id Guid


public class Post
{
public Guid Id { get; set; }
public string Name { get; set; }
}

Modify [Link] make Id Guid


public class CreatePostRequest
{
public Guid Id { get; set; }
}

Modify [Link] make Id Guid


public class PostResponse
{
public Guid Id { get; set; }
}

Create Services folder, add [Link] interface


public interface IPostService

List<Post> GetPosts();

Post GetPostById(Guid postId);

}
Add [Link] class which implements IPostService interface
public class PostService : IPostService
{
private readonly List<Post> _posts;

public PostService()
{
_posts = new List<Post>();
for (var i = 0; i < 5; i++)
{
_posts.Add(new Post
{
Id = [Link](),
Name = $"Post Name {i}"
});
}
}
public List<Post> GetPosts()
{
return _posts;
}

public Post GetPostById(Guid postId)


{
return _posts.SingleOrDefault(x => [Link] == postId);

}
}

Modify [Link] (which was created instead of [Link]) and add AddSingleton method
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
[Link]<ApplicationDbContext>(options =>
[Link](
[Link]("DefaultConnection")));

[Link]<IPostService, PostService>();
}
Modify [Link], as follows
public class PostsController : Controller
{

private readonly IPostService _postService;

public PostsController(IPostService postService)


{
_postService = postService;
}

[HttpGet([Link])]
public IActionResult GetAll()
{
return Ok(_postService.GetPosts());
}

[HttpGet([Link])]
public IActionResult Get([FromRoute] Guid postId)
{
var post = _postService.GetPostById(postId);
if (post == null)
return NotFound();
return Ok(post);
}

[HttpPost([Link])]
public IActionResult Create([FromBody] CreatePostRequest postRequest)
{
var post = new Post{Id = [Link]};

if ([Link] != [Link])
[Link] = [Link]();

_postService.GetPosts().Add(post);

var baseUrl = $"{[Link]}://{[Link]()}";


var locationUri = baseUrl + "/" + [Link]("{postId}", [Link]());
var response = new PostResponse {Id = [Link]};
return Created(locationUri, response);
}

}
[Link] CORE 2.2 REST API TUTORIAL 6 - UPDATING RESOURCES W ITH PUT

Add Contract/v1/Requests/ class [Link]


public class UpdatePostRequest
{
public string Name { get; set; }
}

Modify interface [Link] add UpdatePost method


public interface IPostService
{
List<Post> GetPosts();
Post GetPostById(Guid postId);
bool UpdatePost(Post postToUpdate);

Modify [Link], add updatePost method


public bool UpdatePost(Post postToUpdate)
{
var exists = GetPostById([Link]) != null;
if (!exists)
return false;
var index = _posts.FindIndex(x => [Link] == [Link]);
_posts[index] = postToUpdate;
return true;

Modify [Link], add Update static method


public const string Update = Base + "/posts/{postId}";

Modify [Link], add Update method

[HttpPut([Link])]
public IActionResult Update([FromRoute] Guid postId, [FromBody] UpdatePostRequest request)
{
var post = new Post
{
Id = postId,
Name = [Link]
};
var updated = _postService.UpdatePost(post);
if (!updated)
return NotFound();
return Ok(post);
}
[Link] CORE 3 & 2.2 REST API TUTORIAL 7 - DELETING RESOURCES W ITH DELETE

Modify interface [Link] add DeletePost method


public interface IPostService
{
List<Post> GetPosts();
Post GetPostById(Guid postId);
bool UpdatePost(Post postToUpdate);
bool DeletePost(Guid postId);

Modify [Link], add updatePost method


public bool DeletePost(Guid postId)
{
var post= GetPostById(postId);
if(post == null)
return false;
_posts.Remove(post);
return true;
}

Modify [Link], add Update static method


public const string Delete = Base + "/posts/{postId}";

Modify [Link], add Delete method

[HttpDelete([Link])]
public IActionResult Delete([FromRoute] Guid postId)
{
var isDeleted = _postService.DeletePost(postId);
if (!isDeleted)
return NotFound();
return NoContent();
}

You might also like