How do I create api with c#? Explain With examples
- User
How do I create api with c#? Explain With examples
- Assistant
How do I create api with c#? Explain With examples
To create an API using C#, you can make use of the ASP.NET Core framework. Here is a simple step-by-step guide with examples:
Step 1: Create a new ASP.NET Core Web API project in Visual Studio.
Step 2: Define the model or data structure for your API.
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
Step 3: Define a controller to handle API requests and responses.
[ApiController]
[Route("api/[controller]")]
public class BooksController : ControllerBase
{
private List<Book> books = new List<Book>
{
new Book { Id = 1, Title = "Book 1", Author = "Author 1" },
new Book { Id = 2, Title = "Book 2", Author = "Author 2" },
new Book { Id = 3, Title = "Book 3", Author = "Author 3" }
};
[HttpGet]
public IActionResult GetAllBooks()
{
return Ok(books);
}
[HttpGet("{id}")]
public IActionResult GetBookById(int id)
{
var book = books.FirstOrDefault(b => b.Id == id);
if (book == null)
return NotFound();
return Ok(book);
}
[HttpPost]
public IActionResult AddBook([FromBody] Book book)
{
books.Add(book);
return CreatedAtAction(nameof(GetBookById), new { id = book.Id }, book);
}
[HttpPut("{id}")]
public IActionResult UpdateBook(int id, [FromBody] Book book)
{
var existingBook = books.FirstOrDefault(b => b.Id == id);
if (existingBook == null)
return NotFound();
existingBook.Title = book.Title;
existingBook.Author = book.Author;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteBook(int id)
{
var book = books.FirstOrDefault(b => b.Id == id);
if (book == null)
return NotFound();
books.Remove(book);
return NoContent();
}
}
Step 4: Configure the API routing in the Startup.cs class.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// ...
}
Step 5: Run the API project.
Now your API is created and ready to handle requests. Here are some example requests you can make using tools like Postman:
GET all books: GET http://localhost:5000/api/books
GET a book by ID: GET http://localhost:5000/api/books/1
POST a new book: POST http://localhost:5000/api/books
Request body: { "id": 4, "title": "Book 4", "author": "Author 4" }
PUT (update) a book: PUT http://localhost:5000/api/books/2
Request body: { "id": 2, "title": "Updated Book 2", "author": "Updated Author 2" }
DELETE a book: DELETE http://localhost:5000/api/books/3
These examples cover basic CRUD operations (Create/Read/Update/Delete) for an API. You can extend this with additional functionality as required.
Not yet included in a published release.