Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Programming APIs with C# and .NET
Programming APIs with C# and .NET

Programming APIs with C# and .NET: Develop high-performance APIs that ensure seamless application communication and enhanced security

Arrow left icon
Profile Icon Jesse Liberty Profile Icon Joseph Dluzen
Arrow right icon
€33.99
Paperback Nov 2024 166 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Jesse Liberty Profile Icon Joseph Dluzen
Arrow right icon
€33.99
Paperback Nov 2024 166 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Programming APIs with C# and .NET

What We’ll Build

In this chapter, we will provide a context for the rest of the book. That context is a simple application for buying and selling cars. We will not build out this application but, in fact, we’ll have only one type of object (Car) and one table in our database. This will allow us to focus on the API rather than getting hung up on database design.

In this chapter, we’re going to cover the following main topics:

  • What an API is and what it is for
  • The backend database that we will use throughout the book
  • The application that we will build throughout the book
  • The Car object that we will use to demonstrate CRUD operations

We will use only free software, as shown in the Technical requirements section, and we will take advantage of open source utilities such as Dapper and AutoMapper, both introduced in Chapter 1.

Technical requirements

For this chapter, you’ll need Visual Studio and SQL Server Management Studio (SSMS), as well as Postman. Remember that SSMS was installed with Visual Studio.

Note that you can also manage your database from within Visual Studio using the Server Explorer and the SQL Server Object Explorer.

The code files for this book are available in the book’s GitHub repository : https://github.com/PacktPublishing/Programming-APIs-with-C-Sharp-and-.NET/tree/main/Chapter02

What is an API and what is it for?

The purpose of an API is to decouple the backend of an application (e.g., a database) from the frontend (e.g., a web application or mobile application), as illustrated in Figure 2.1.

Figure 2.1 – Separation of concerns

Figure 2.1 – Separation of concerns

The client does not talk directly to the database but rather talks to the API, which, in turn, talks to the database. The huge advantage of this approach is that you can modify the database and the client does not have to change. Alternatively, you can modify the front end (for example, a website) without changing the database.

These modifications take place throughout the development of a large project and continue after delivery. It is imperative, especially with a mobile application, that you can modify the backend without forcing the user to update the application. Even with web applications, however, this can be critical, as the team maintaining the database may well not be the team maintaining...

The application

The database we’ll be creating will be used in a simple (fictional) application for buying and selling cars. The database will keep a list of automobiles along with details of their engine, performance, and so on. A short example of this data is shown in Figure 2.2.

Figure 2.2 – A subset of the data table we’ll be using

Figure 2.2 – A subset of the data table we’ll be using

Creating the Car Table

The data for the Car table is from the free Automobile dataset at https://kaggle.com. Download the data and import it into a database named Cars and a table named Car. The columns should take care of themselves.

The datasets on Kaggle change frequently, so your list of cars may look a bit different. All the datasets are all presented as .csv files, so just download one and open SSMS in order to do the import. Here are the steps:

  1. Log into SSMS and create a database.
  2. Create a table named CARS.
  3. Start the Import Data Wizard. To do so, right-click on the table...

Database structure

Our database consists of just one table: Car. As shown in Figure 2.2, that table must store various attributes of each car (name, miles per gallon, number of cylinders, and so on). Figure 2.3 shows the table:

Figure 2.3 – Car table columns

Figure 2.3 – Car table columns

Notice the is_deleted column. We’ll be using “soft delete” – that is, rather than removing a row on deletion we’ll just set is_deleted to true (1). That allows us to easily restore that column just by changing that value back to 0 (false).

Other than id, all of the columns are strings, which will make working with them easier.

Car object

Corresponding to the Car table, our code has a Car entity (Cars/Data/Entities/Car.cs):

namespace Cars.Data.Entities;
public class Car
{
    public int Id { get; set; }
    public string name { get; set; } = null!;
    public string mpg { get; set; } = null...

The ASP.NET application

To get started, create a new ASP.NET project using the ASP.NET Core Web API template. Put the files wherever is convenient for you and choose the latest version of .NET (this book was written with .NET 8).

The basic structure of our application will be as follows:

  • Controllers with endpoints
  • Services
  • Repositories

We’ll review endpoints and all the rest of this as we go.

Program.cs

You won’t have to edit Program.cs for this application but it is worth a few minutes of your time to review it:

using Cars.Data;
using Cars.Data.Interfaces;
using Cars.Data.Repositories;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Load DB configuration and register the connection factory for 
...

Folders

To organize our application, we will create the following folders:

  • Controllers
  • Data
  • Interfaces
  • Repositories
  • Services

Let’s briefly explain what these are:

  • The client is the application calling the API (for example, the website or mobile application). The Controllers folder will hold methods that act as endpoints (an endpoint is what the client connects to via a URL).
  • The Data folder will hold the definition of our entities – in our case, the Car object shown earlier.
  • The Interfaces folder is just what it sounds like: it will hold the interfaces to our C# objects.
  • The Repositories folder will hold the code between our methods and the database calls.
  • The Services folder will hold supporting code.

The flow will be as follows:

  1. The client calls a method in a controller.
  2. The method calls a service to handle the business logic.
  3. The service calls a method in the repository, which, in turn,...

Summary

In this chapter, you saw what an API is and how it is used to separate the front end (e.g., a web site) from the backend (e.g., a database). We also looked at the simple database and application that we’ll use throughout the book.

In order to demonstrate CRUD operations, we’ll build a simple application focused on a Car object as if we were working with an inventory of cars. We imported it from https://kaggle.com.

This lays the groundwork for the rest of the chapters and for the simple application that we will build. Our focus will be strictly on creating APIs, so we will spend little time on database technology or even on the frontend.

You try it

This is a good time to create your application and the database. If you are adventurous, create a similar but different application, database, and data entity. This will ensure that you cement the elements we’ll be using.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn API design principles and architecture for high-performance applications
  • Develop robust APIs using best practices for security, scalability, and maintainability
  • Implement both traditional and minimal APIs with real-world scenarios
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

APIs are at the heart of modern software development, enabling seamless communication between applications. In the C# and .NET ecosystem, mastering API development is key to building scalable, reliable systems that meet both client and enterprise needs. Written by C# and .NET experts Jesse Liberty and Joseph Dluzen, this book draws on their extensive experience as hands-on programmers to equip you with the tools, techniques, and best practices for creating powerful APIs. Starting with API fundamentals, it covers everything you need to design, build, and consume APIs using .NET technologies such as ASP.NET Core, and explores both controller and Function API implementations. You'll integrate essential tools such as Postman for testing to streamline your development workflow. Through practical examples and exercises, the book guides you from database creation to deploying APIs on Azure. By the end of this book, you’ll have gained real-world skills to develop secure, high-performance APIs that scale with your applications for both personal projects and enterprise-level systems.

Who is this book for?

This book is for .NET developers, software engineers, and backend developers looking to master API development using C# and ASP.NET Core. It caters to those with a basic understanding of C# and familiarity with the .NET ecosystem. Even though no prior experience with API frameworks is required, knowledge of ASP.NET Core will be helpful.

What you will learn

  • Understand core API concepts and how to apply them in .NET projects
  • Design RESTful APIs with a focus on scalability
  • Build APIs with ASP.NET Core
  • Explore alternative options for API development using Azure Functions, including stateful workflows with Durable Functions
  • Integrate databases into API projects, ensuring efficient data flow
  • Implement security measures such as authentication and authorization
  • Deploy APIs to Azure and learn the essentials of cloud integration
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 22, 2024
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781835468852
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Nov 22, 2024
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781835468852
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Table of Contents

13 Chapters
Chapter 1: Getting Started Chevron down icon Chevron up icon
Chapter 2: What We’ll Build Chevron down icon Chevron up icon
Chapter 3: Implementing with REST Chevron down icon Chevron up icon
Chapter 4: Documentation with Swagger Chevron down icon Chevron up icon
Chapter 5: Data Validation Chevron down icon Chevron up icon
Chapter 6: Azure Functions Chevron down icon Chevron up icon
Chapter 7: Azure Durable Functions Chevron down icon Chevron up icon
Chapter 8: Advanced Topics Chevron down icon Chevron up icon
Chapter 9: Authentication and Authorization Chevron down icon Chevron up icon
Chapter 10: Deploying to Azure Chevron down icon Chevron up icon
Chapter 11: What’s Next? Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela