Click here to Skip to main content
15,888,610 members
Articles / Programming Languages / Markdown

How to Create API in .NET Core

Rate me:
Please Sign up or sign in to vote.
4.41/5 (15 votes)
27 Aug 2020CPOL3 min read 12.2K   14   3
Learn to create an API in .NET Core
At the end of this article, you will learn how to create an API in .NET Core

Goal to Achieve

We have a fictional company that needs to expose a set of methods to perform these operations:

  • Create a product
  • Read a product
  • Update a product
  • Delete a product

The external applications which are going to consume these API methods have a screen like this:

project-showcase

In this case, we have an entity called Product with 4 fields:

  • Product (int)
  • Name (string)
  • ImageUrl (string)
  • Price (decimal)

Before we start coding, I encourage you to refresh the basic concepts about API and JSON format.

What are APIs?

I have read a lot of definitions about this concept and I have preferred to keep this in my mind:

APIs is the specification of how one piece of software can interact with another.

In our example, we are going to create a set of pieces (“methods”) that will be in charge of doing a specific task interacting with external applications.

Operation Http Verb
Create a product POST
Read a product GET
Update a product UPDATE
Delete a product DELETE

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight format for storing and transporting data
  • JSON is often used when data is sent from a server to a web page
  • JSON is “self-describing” and easy to understand

So, let´s start coding.

Step 1: Run Dotnet Command

Open the command line window and go to your repositories folder and create a new API project by typing the next dotnet command:

dotnet new webapi - n crudstore

Step 2: Explore Your Project

Go inside your project crudstore, by typing:

cd crudstore

Open your project in vscode, by typing:

code .

Step 3: Set Up Your Environment

Click on the extension panel and explore a great amount of tools that will help you to prepare your environment and be more productive.

Personally, I would recommend you to install:

  • C#
  • C# Extension

c#-extension

Step 4: Creating the Model

C#
namespace Models
{
public class Product

{
public int Idproduct { get; set; }
public string Name { get; set; }
public string Imageurl { get; set; }
public decimal Price { get; set; }
}
}

Step 5: Creating the Controller

I will use static collections of products to illustrate this example, but in a real scenario, certainly, you will have to add more code to connect with the database.

C#
static List<product> _products = new List<product>(){
            new Product(){ Idproduct =0, Name= "hard disk", Price= 100  },
            new Product(){ Idproduct =1, Name= "monitor", Price= 250  },
        };

After that, add the next code to handle all the requests.

Be aware that you have to use some namespaces in the header:

C#
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models;</code>
C#
[Produces("application/json")]
    [ApiController]
    [Route("api/products")]
    public class productController : Controller
    {
        static List<Product> _products = new List<Product>(){
            new Product(){ Idproduct =0, Name= "hard disk", Price= 100  },
            new Product(){ Idproduct =1, Name= "monitor", Price= 250  },
        };

        [HttpGet("GetAll")]
        public IActionResult GetAll()
        {
            return Ok(_products);
        }

        [HttpPost]
        public IActionResult Post([FromBody] Product product)
        {
            _products.Add(product);
            return StatusCode(StatusCodes.Status201Created);
        }

        [HttpPut]
        public IActionResult Put([FromBody] Product product)
        {
            var entity = _products.Where
                         (x => x.Idproduct == product.Idproduct).FirstOrDefault();
            entity.Name =  product.Name;
            entity.Price = product.Price;
            entity.Imageurl =  product.Imageurl;
            return StatusCode(StatusCodes.Status200OK);
        }

        [HttpDelete]
        public IActionResult Delete([FromBody] Product product)
        {
            var entity = _products.Where
                         (x => x.Idproduct == product.Idproduct).FirstOrDefault();
            _products.Remove(entity);
            return StatusCode(StatusCodes.Status200OK);
        }
    }

Step 6: Add Swagger to Your Project

Swagger is a nugget very useful to document and describe all the methods in your API.
In the command line and inside of your project, type the next command:

C#
dotnet add package Swashbuckle.AspNetCore

As a result, you will see a message like this:

Go to the startup.cs class in your project and make some changes to allow that swagger can be configured appropriately.

In the method Configureservices, add this code:

C#
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
            }));
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen();

After that, go to the Configure method in the Startup class and add this code:

C#
// Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

Finally, your Startup class should be like this:

C#
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. 
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
            }));
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen();
        }

        // This method gets called by the runtime. 
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

Step 7: Testing your API

Type the next command in the command line window:

C#
dotnet run

Step 8: Verifying the Results

Open the browser and type the url https://localhost:5001/swagger/index.html, you will see the set of methods that we created previously.

swagger-crud

Method GetAll

Url: https://localhost:5001/api/products/GetAll

C#
[
{
"idproduct": 0,
"name": "hard disk",
"imageurl": null,
"price": 100
},
{
"idproduct": 1,
"name": "monitor",
"imageurl": null,
"price": 250
}
]

Method Post

Url: https://localhost:5001/api/products

C#
{
  "idproduct": 0,
  "name": "watch",
  "imageurl": "http://url",
  "price": 150
}

You can explore all the features that Swagger offers to test the APIs, therefore you have other interesting alternatives like Postman and Fiddler to test the APIs.

I hope you enjoy this code!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Uruguay Uruguay
I am Software Developer with a passion for technology with strong backend (PHP, MySQL, PostgreSQL and SQL Server) and frontend (HTML5, CSS3, AngularJs and KnockOutJs) experience. I combine my education with expertise in CSS3, HTML5, Javascript to build creative and effective websites and applications.

If you wish to contact me then please do so on ricardojavister@gmail.com or feel free to skype me on
ricardo-torres-torres.

Comments and Discussions

 
QuestionHTTP Verb UPDATE Pin
baernhardj6-Nov-20 2:58
baernhardj6-Nov-20 2:58 
QuestionBeginners questions Pin
r_alf28-Aug-20 22:24
r_alf28-Aug-20 22:24 
QuestionUse of services.AddCors Pin
Chipo Hamayobe28-Aug-20 7:24
Chipo Hamayobe28-Aug-20 7:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.