Building a showcase API
REST APIs revolve around HTTP requests and responses, which power the web and are implemented in every web framework using the HTTP protocol. To showcase the capabilities of FastAPI, you will now create simple endpoints that focus on specific parts of code that achieve the desired functionalities. Rather than the usual CRUD operations, the next sections will focus on the process of retrieving and setting request and response elements.
Retrieving path and query parameters
The first endpoint will be for retrieving a fictional car by its unique ID.
- Create a file called
chapter4_02.py
and insert the following code:from fastapi import FastAPI app = FastAPI() @app.get("/car/{id}") async def root(id): return {"car_id": id}
The third line of the code snippet defines a dynamic path defined with
car/:id
, while{id}
is a standard Python string-formatted dynamic parameter in the sense that it can be anything—...