Skip to main content

How a Client, an API and a Database Work Together – Web Basics | Lesson 2

Published / updated

Introduction​

When a teacher clicks "Class 10-A" in the SMS, a list of students appears in under a second. Behind that click, three programs talk to each other.

This lesson follows that one click, step by step. You will meet the words you will use in every later lesson: client, server, request, response, API, and database.

By the end of this lesson, you will be able to:

  • Explain what a client, a server, an API, and a database each do.
  • Read a simple HTTP request and response.
  • Name the four common HTTP methods and what each is for.
  • Explain what the status codes 200, 201, 400, 404, 422, and 500 mean.
  • Trace one SMS request from the screen to the database and back.

Why this matters​

Every feature you build later follows the same path. Attendance, marks, fees, and reports all start as a request from a screen and end as rows in a table.

When something breaks, you need to know which layer to look at. Is the screen sending the wrong thing, is the API rejecting it, or is the database slow?

You cannot answer that until you can see the whole path.

The concept​

A client is the program that asks for something. In the SMS, the client is the website in the teacher's browser, or the parents' mobile app.

A server is a program that waits for requests and answers them. Our server runs the API: the set of addresses that clients call.

A database is where the data is stored permanently. Ours is SQL Server. Only the API talks to the database; the client never does.

Example: the restaurant​

Think of a restaurant:

RestaurantSMSJob
CustomerClient (browser or app)Asks for something
WaiterAPITakes the order, checks it, brings back the result
Kitchen and store roomDatabaseKeeps the ingredients and prepares the dish

The customer never walks into the kitchen. In the same way, the browser never connects to the database.

Requests and responses​

The client and the API talk using HTTP (HyperText Transfer Protocol). HTTP is a set of rules for sending a request and getting back a response.

Every request has:

  • A method: what you want to do.
  • A URL: which thing you want it done to.
  • Headers: extra information, like who you are.
  • Sometimes a body: the data you are sending.

Example: HTTP methods​

MethodMeaningSMS example
GETRead dataGet the student list of Class 10-A
POSTCreate something newRecord a new fee payment
PUTReplace or update somethingUpdate a student's address
DELETERemove somethingCancel an exam that was created by mistake

Every response has a status code: a three-digit number that says how it went.

Example: status codes​

CodeNameWhen the SMS returns it
200OKThe student list was found and sent
201CreatedA new fee payment was saved
400Bad RequestA required field, such as the student's first name, was left empty
404Not FoundStudent with that Id does not exist
422Unprocessable EntityMarks of 105 were sent for a paper out of 100: well-formed, but against a school rule
500Internal Server ErrorA bug in our code, or the database is down

A simple rule: codes starting with 2 mean success, 4 mean the client sent something wrong, and 5 mean the server failed.

The data in requests and responses is usually JSON (JavaScript Object Notation). JSON is plain text that holds names and values, like "rollNumber": 1.

Apply it to the SMS​

Let us follow Anitha Rao, class teacher of 10-A, as she opens her class list.

Example: the request​

When she clicks "Class 10-A", the browser sends this request to the API:

What the browser sends
GET /api/classes/10/sections/A/students HTTP/1.1
Host: api.nexcodingschool.example
Accept: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.example-token

Read it line by line:

  • GET is the method: she wants to read data.
  • /api/classes/10/sections/A/students is the address: Class 10, its Section A, and that section's students.
  • Accept says she wants JSON back.
  • Authorization carries her login token, so the API knows who is asking. You will build login in Module 12.

An address can also carry options after a ?, called the query string. For example, /api/students?classId=10&page=2 asks for the second page of Class 10's students.

Example: the full path of one request​

Here is everything that happens after the click:

  1. Browser to API. The request above travels over the internet to the API server.
  2. API checks the request. Is the token valid? Is Anitha allowed to see this class? If not, the API answers 401 or 403 and stops.
  3. API runs the C# logic. It works out which academic year is current and builds the question for the database.
  4. API asks the database. In plain words: "Give me this year's students in Class 10, Section A, by roll number." You will write this exact query yourself in Module 4.
  5. Database answers. SQL Server finds four rows and sends them back to the API.
  6. API turns rows into JSON and sends the response with status code 200.
  7. Browser shows the list on the screen.

Example: the response​

This is the response the browser receives:

What the API sends back
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

[
{ "id": 1, "admissionNumber": "ADM-2017-0001", "fullName": "Aarav Sharma", "rollNumber": 1 },
{ "id": 2, "admissionNumber": "ADM-2017-0002", "fullName": "Diya Patel", "rollNumber": 2 },
{ "id": 3, "admissionNumber": "ADM-2017-0003", "fullName": "Kabir Singh", "rollNumber": 3 },
{ "id": 4, "admissionNumber": "ADM-2017-0004", "fullName": "Meera Iyer", "rollNumber": 4 }
]

200 OK says it worked. The part in square brackets is a JSON array: a list. Each item in curly braces is one student.

Example: three tiers​

This design is called three-tier architecture: three separate layers, each with one job.

TierSMS partMust never
PresentationWebsite, mobile appConnect to the database directly
ApplicationASP.NET Core Web API with C# logicTrust data from the client without checking it
DataSQL Server database SchoolDbBe open to the internet

Keeping the database behind the API protects it. The API decides who can see what. It also lets the website and the mobile app share the same rules.

Common mistakes​

  1. Thinking the browser talks to the database. It never does. Fix: always draw the API in the middle when you explain a feature.
  2. Using GET to change data. A GET request can be repeated by the browser or cached. Fix: use POST, PUT, or DELETE when data changes.
  3. Returning 200 for every answer. Then the client cannot tell success from failure. Fix: return the status code that matches what happened.
  4. Trusting checks done only on the screen. Anyone can send a request without using your screen. Fix: the API must check every request again.

In real projects​

From 16 years of .NET projects

When a production issue comes in as "the page is slow", the first thing I do is split the time by layer. The browser's developer tools show how long the API took, and the API logs show how long the database call took.

Nine times out of ten, the network is fine. The problem is a missing index, or a query that returns far more rows than the screen needs.

The second most common cause of bugs I have seen is validation that lives only in the frontend. A mobile app was released later without the same checks, and bad data went straight into the database. The API is the one place every client must pass through, so the rules belong there, with the database as the last safety net.

Best practices​

  • Keep the database private; only the API connects to it.
  • Use the HTTP method that matches the action.
  • Return accurate status codes, so clients can react correctly.
  • Validate every request in the API, even if the screen already checked it.

Recap​

  • The client asks, the API answers, and the database stores the data.
  • HTTP requests have a method, a URL, headers, and sometimes a body.
  • GET reads, POST creates, PUT updates, DELETE removes.
  • Status codes: 2xx success, 4xx client error, 5xx server error.
  • Data travels as JSON.
  • Three-tier architecture keeps the database behind the API.

Homework​

Library module task: A student opens the library page and searches for available copies of the book "Wings of Fire". Write the 7 steps of this request, like the student-list example above. Then write the HTTP method, the URL, and the status code you expect.

A correct result looks like: 7 numbered steps from browser to database and back, plus GET, a URL such as /api/books?search=Wings%20of%20Fire, and status code 200.

Show a sample solution
  1. The browser sends GET /api/books?search=Wings%20of%20Fire.
  2. The API checks the student's login token.
  3. The API's C# code prepares the search.
  4. The API asks the database for books whose title matches, with their available copies.
  5. The database returns the matching rows.
  6. The API converts the rows to JSON and responds with 200 OK.
  7. The browser shows the books and how many copies are available.

If no book matches, the API still returns 200 OK with an empty list []. A search that finds nothing is not an error.

Quiz​

  1. In the SMS, which part is allowed to connect to SQL Server?

    1. The browser
    2. The mobile app
    3. The API
    4. Any of them
    Show answer

    Answer: C. The API Only the API talks to the database; clients go through the API.

  2. Which HTTP method should record a new fee payment?

    1. GET
    2. POST
    3. DELETE
    4. HEAD
    Show answer

    Answer: B. POST POST creates something new.

  3. The API receives marks of 105 for a paper out of 100. Which status code fits best?

    1. 200 OK
    2. 201 Created
    3. 422 Unprocessable Entity
    4. 500 Internal Server Error
    Show answer

    Answer: C. 422 Unprocessable Entity The request is well-formed but breaks a school rule: a 4xx client error, 422 in the SMS.

  4. In the URL /api/students?classId=10&page=2, what is the part after the question mark?

    1. The method
    2. The query string
    3. The header
    4. The status code
    Show answer

    Answer: B. The query string The query string carries options such as the class and the page.

  5. What does a status code starting with 5 mean?

    1. Success
    2. The client sent something wrong
    3. The server failed
    4. The data was created
    Show answer

    Answer: C. The server failed 5xx codes mean the server could not complete a valid request.

Interview questions​

Questions are grouped by experience level. Click a question to see a model answer. All questions: Web API interview questions, Architecture interview questions.

Fresher (0-2 yrs)​

F What are a client and a server? concept

A client is a program that sends requests, such as a browser or a mobile app. A server is a program that waits for requests and answers them, such as our ASP.NET Core API. In the SMS, the teacher's browser is the client and the API is the server.

See the example · Permalink

F What is an API? concept

An API (Application Programming Interface) is a set of addresses that other programs call to read or change data. A Web API works over HTTP and usually exchanges JSON. For example, GET /api/classes/10/sections/A/students returns the students of Class 10-A.

See the example · Permalink

F What do the HTTP status codes 200, 201, 400, 404 and 500 mean? concept

200 OK means the request worked. 201 Created means something new was saved. 400 Bad Request means the client sent invalid data, 404 Not Found means the item does not exist, and 500 Internal Server Error means the server failed. Codes starting with 2 are success, 4 are client errors, 5 are server errors.

See the example · Permalink

Mid (3-5 yrs)​

M What is the difference between GET and POST? concept

GET reads data, has no body, and is safe to repeat; browsers may cache or bookmark it. POST creates something new and sends data in the body; repeating it can create duplicates. Never change data with GET, because a refresh or a link preview could repeat it.

See the example · Permalink

M What does it mean that HTTP is stateless, and how does the server know who is calling? concept

Stateless means each request stands alone; the server does not remember earlier requests. So every request must carry the caller's identity, usually a token in the Authorization header or a cookie. The API validates that token on every request.

See the example · Permalink

M Walk me through what happens when a teacher opens the class list. concept

The browser sends a GET request with the class filter and the login token. The API checks the token and the teacher's permission, runs the C# logic, and queries the database for the enrolled students. SQL Server returns the rows, the API converts them to JSON with status 200, and the browser displays the list.

See the example · Permalink

Senior (6-9 yrs)​

S Where should validation happen: in the screen, the API, or the database? scenario

In all three, for different reasons. The screen validates for quick feedback, the API validates every request because any client can call it directly, and the database constraints are the last safety net. For example, "marks cannot exceed 100" is shown on the screen, rejected by the API with 400, and blocked again by the database.

How to answer: Explain the three purposes (user experience, authority, integrity). Use one SMS rule and show it at each layer. Then cover the trade-off: duplicated rules must stay in sync, so the API is the single source of business rules and the database holds only rules that must never be broken (uniqueness, required values, valid ranges).

See the example · Permalink

S The class list page takes 8 seconds to load. How do you find which layer is slow? scenario

Measure each layer instead of guessing. The browser's network tab shows how long the API call took; the API logs show how much of that was the database call; the database's execution plan shows why the query is slow. The usual causes are a missing index, a query returning far more rows than the screen needs, or many small queries in a loop.

How to answer: Describe the top-down method (browser, API, database) with the tool for each layer. Give the SMS case: the list of 40 students in 10-A should not scan 10,000 enrollments. End with the fix and how you would prove it worked: before and after timings.

See the example · Permalink

Architect / Lead (10+ yrs)​

A Why should a website or mobile app never connect directly to the database? design

The database credentials would have to live on every user's device, where anyone can extract them. There would be no single place to apply business rules and permissions, and every app would break whenever a table changes. An API keeps the database private, applies the rules once for every client, and gives apps a stable contract.

How to answer: State the risks (security, duplicated rules, tight coupling to the schema). Use the SMS: a parent's app must only see their own child's marks, which only the server can enforce. Acknowledge the cost: an extra layer adds a little latency and code to maintain, which is worth it for any system with more than one client or sensitive data.

See the example · Permalink

Resources​

  • Code for this lesson: git tag lesson-2-client-api-database (code repository coming soon)
  • Video: coming soon

What's next​

Now that you know how the pieces talk, you will meet the school and write down what it needs. Lesson 3: School requirements and modules

Want live sessions, code reviews, and interview preparation? Join the next batch at Sahasra Technologies.