Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 50 ยท Getting started

Your first endpoint and the test client

Create a FastAPI app, add path operations with decorators, return JSON, and call the app in-process with httpx to read status, headers and body.

An API is a set of endpoints: pairs of an HTTP method and a URL, each backed by a function. In FastAPI you create an app object, then attach functions to it with decorators. Whatever a function returns becomes the response. That is the whole core idea, and in this lesson you will build it up step by step, then learn how to call your app from code so you can see exactly what a client would see.

You met a first taste of this in What FastAPI is and how to set it up. Now we slow down and look at every part.

The app and a path operation

An app is an instance of FastAPI. A path operation is a function registered for one method and one path. The decorator names the method, and its argument is the path:

Python
from fastapi import FastAPI

app = FastAPI()


@app.get("/ping")
async def ping():
    return {"pong": True}

@app.get("/ping") means: when a GET request arrives for /ping, call this function. The return value, a dictionary here, is converted to JSON and sent back with status 200 and the header content-type: application/json.

There is one decorator per HTTP method: @app.get, @app.post, @app.put, @app.patch and @app.delete, plus the rarer @app.head and @app.options. By convention they mean:

Method Typical meaning
GET Read something; never changes data
POST Create something, or run an action
PUT Replace something completely
PATCH Change part of something
DELETE Remove something

You can return dictionaries, lists, strings, numbers, booleans, None and Pydantic models. FastAPI turns all of them into JSON.

Calling the app in-process

On a server, a client would send the request over the network. Here we skip the network: httpx.ASGITransport hands the request directly to the app. The client object works like the familiar requests library, but with await.

Python Call an endpoint and inspect the response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The response object has everything a real client sees: status_code, headers, the raw text and a json() helper. The base_url is a placeholder that only makes URLs complete; nothing is ever contacted.

A reusable helper

Writing the client setup every time is noisy. From now on, many examples use a small helper that sends one request and prints a short summary. Keep this idea in mind; it is just a function.

Python A call() helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look closely at the last two lines. Asking for a URL that does not exist gives 404 Not Found. Using the wrong method on a URL that does exist gives 405 Method Not Allowed. You wrote no code for either; the router handles them. Both bodies use the key detail, which is FastAPI's standard shape for errors.

Notice also that a returned string is valid JSON: it is sent with quotes, as "just a string".

What happens during a request

sequenceDiagram
    participant C as Client
    participant A as FastAPI app
    participant R as Router
    participant E as Your endpoint
    C->>A: GET /ping
    A->>R: find a matching route
    R->>E: call ping()
    E-->>A: {"pong": true}
    A-->>C: 200 + JSON body

The app finds the route, calls your function and serializes whatever it returns.

In more detail, FastAPI does these steps for each request:

  1. Match the method and path against your registered routes. No match gives 404, or 405 if the path exists for other methods.
  2. Read the parameters your function declares (you will add some in the next lessons) and validate them. Invalid input gives 422 before your function runs.
  3. Call your function with the validated values.
  4. Serialize the return value to JSON and build the response.

Only step 3 is your code. Everything else is the framework.

Choosing status codes

By default, successful endpoints answer 200. Often another code is more accurate. For example, creating a resource should answer 201 Created. Set it in the decorator:

Python Setting the status code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The app keeps notes in a plain list, so it remembers across calls inside one run. A real service would use a database; SQLAlchemy with FastAPI covers that. Status codes get a full lesson later: Status codes and error handling.

Module state lives per process. A list at module level is fine for learning, but a server may run several worker processes, each with its own copy, and it loses everything on restart. Never rely on it for real data.

async def or def?

All endpoints in this track are async def, because the browser cannot run threads. On a real server you may also write a plain def; FastAPI runs it in a thread pool so it cannot block the event loop. The rule of thumb: use async def when you await something inside, and plain def when you call blocking code. We cover this in depth in async def vs def endpoints.

Testing at home

Locally you would use the synchronous TestClient that ships with FastAPI, which needs no await and is perfect for pytest:

Python
from fastapi.testclient import TestClient

client = TestClient(app)
response = client.get("/ping")
assert response.status_code == 200
assert response.json() == {"pong": True}

It uses the same idea as our in-process client. The block is read-only here because TestClient runs the app in a helper thread. Testing FastAPI apps compares both styles properly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @app.get("/ping") do?

    The decorator registers the function as the handler for one HTTP method and path. The framework calls it when a matching request arrives.
  2. 2. A client sends POST to a path that only has a GET endpoint. What status does FastAPI return?

    The path exists but not for that method, so the router answers 405. A path that matches nothing at all gives 404.
  3. 3. How do you make an endpoint answer 201 instead of 200?

    The decorator accepts status_code. That value is used for successful responses from that endpoint.
  4. 4. What does httpx.ASGITransport(app=app) allow?

    It passes requests directly to the ASGI app, so routing, validation and your code run for real while no socket is opened.

Summary

  • app = FastAPI() creates the application; @app.get, @app.post and friends register path operations.
  • Returned dictionaries, lists, strings and models become JSON automatically.
  • An httpx.AsyncClient with ASGITransport calls your app in-process; read status_code, headers, text and json().
  • Unknown paths give 404 and wrong methods give 405 without any code from you.
  • Set a success code with status_code= in the decorator.
  • A request is matched, validated, handled by your function and serialized.

Next, take values out of the URL itself with Path parameters.