Welcome to the first lesson of our course, "Exposing Your Code Translator with FastAPI"! This is the second course of the "Building a Smart Code Translator with Haystack, FastAPI and Gradio" course path. In the previous course, we built a smart code translation pipeline using Haystack. Now, it's time to make that powerful functionality accessible to the world by wrapping it in a web API. This is a crucial step — APIs are how modern applications communicate, whether it's a mobile app, a web frontend, or another backend service.
In this lesson, you'll learn what APIs are, why REST is such a popular approach, and how FastAPI makes building APIs in Python both easy and robust. By the end, you'll have created your first API endpoints and learned how to test them like a pro. Let's get started on this exciting new phase of our project!
Before we write any code, let's clarify what an API is and why RESTful APIs are so widely used. An API (Application Programming Interface) is a set of rules that lets different software systems talk to each other. Imagine ordering food at a restaurant: you (the client) tell the waiter (the API) what you want, and the kitchen (the server) prepares your meal and sends it back through the waiter.
REST (Representational State Transfer) is a style for designing APIs that use standard HTTP methods to interact with resources. In REST, each resource (like a user, a document, or a translation job) is identified by a URL, and you use HTTP methods to perform actions:
- GET: Retrieve data (like reading a message). For example,
GET /users/123
may fetch information about the user with ID 123. - POST: Submit information (like submitting a form). For example,
POST /users
with a JSON body (also called payload) such as{"name": "Alice", "email": "alice@example.com"}
may create a new user.
Other methods like PUT
, DELETE
, and PATCH
exist, but for now, we'll focus on GET
and POST
, as they're the most common and practical for our needs.
RESTful APIs are popular because they are simple, scalable, and language-agnostic. This means you can build a backend in Python and have clients in JavaScript, Java, or even mobile apps — all communicating smoothly.
Now that you know what APIs and REST are, let's look at the specific tool we'll be using: FastAPI. FastAPI is a modern Python framework designed for building APIs quickly and efficiently. It stands out for its speed, ease of use, and automatic documentation.
Some reasons developers love FastAPI:
- Performance: It's one of the fastest Python frameworks, thanks to its async support.
- Automatic docs: It generates interactive documentation for your API, making it easy to explore and test endpoints.
- Type hints: FastAPI uses Python's type hints to validate data and generate clear documentation.
- Developer-friendly: Its syntax is clean and intuitive, making it approachable for beginners and powerful for experts.
With FastAPI, you can focus on your application's logic, while the framework handles much of the heavy lifting behind the scenes.
Let's create a simple FastAPI application with a single endpoint to check that everything is working. This is a great way to verify your setup and get comfortable with the basics.
Here, you create an app instance and define a route using the @app.get("/hello")
decorator. When someone visits /hello
, they'll receive a friendly JSON message. The docstring helps document the endpoint, and FastAPI will include it in the automatic docs.
To run your FastAPI app, you'll use a server called Uvicorn. Uvicorn is an ASGI (Asynchronous Server Gateway Interface) server that is both lightweight and extremely fast, making it a popular choice for serving FastAPI applications in both development and production environments.
You can launch your FastAPI app using a simple Python script. Here’s a minimal example:
- The
"api.app:app"
argument tells Uvicorn where to find your FastAPI app. In our environment, the app is defined inapp.py
inside anapi
folder, so this is the correct path. If your project structure is different, make sure to adjust the path accordingly. host="127.0.0.1"
makes your API accessible only from your local machine. This is the safest option for development, as it prevents external devices from connecting to your API.port=3000
specifies the port number. You can change this if you need to avoid conflicts with other services.reload=True
enables auto-reloading, so the server will automatically restart whenever you make changes to your code. This is very helpful during development, but you should turn it off in production.
Once the server is running, you should see output in your terminal indicating that Uvicorn is serving your FastAPI app and listening for incoming requests. You can now access your API endpoints (like /hello
) in your browser or using tools like curl
.
GET
requests are perfect for fetching information, but what if you want to send data to your API? That's where POST
requests come in. Let's add a POST
endpoint that echoes back the data it receives — this is a practical way to see how FastAPI handles incoming JSON.
Notice the use of async
and await
— this allows FastAPI to handle many requests efficiently: by defining your endpoint as an async
function, FastAPI can process multiple requests concurrently without blocking the server, which is especially important when your API needs to handle I/O-bound operations like reading from a database or waiting for external services. This leads to better scalability and responsiveness, even under heavy load. The endpoint reads the JSON body from the request, then returns the keys and values as separate lists. This pattern is common in APIs that process user input or data from other services.
Note: In this lesson, we're using the
Request
object and manually parsing the JSON for simplicity. FastAPI also supports more robust and automatic ways to handle request data using Pydantic models or type annotations, which provide validation and better documentation. We'll introduce those best practices later in the course.
Once your API is running, you need a way to test it. While there are many tools for this, curl
is a simple and powerful command-line utility that lets you make HTTP requests directly from your terminal.
To test the GET
endpoint:
You should see a JSON response like:
To test the POST
endpoint, use:
This sends a JSON payload to your API, and you should get back:
Using curl
is a quick way to verify your endpoints work as expected before building more complex clients or user interfaces.
One of FastAPI's standout features is its automatic, interactive documentation. As soon as your app is running, you can visit /docs
in your browser (for example, http://127.0.0.1:3000/docs
) to see a live, interactive interface powered by Swagger UI.
This documentation shows all your endpoints, their expected inputs and outputs, and even lets you try them out directly from the browser. There's also an alternative view at /redoc
with a different layout. This makes it much easier to understand, test, and share your API with others — no extra work required for simple endpoints like the ones we've built so far.
You've just taken your first steps into building RESTful APIs with FastAPI, learning how to create endpoints, handle data, and test your work efficiently. These skills are the foundation for making your code translation service accessible and useful to a wide range of applications.
As you move forward, you'll build on this knowledge to add more advanced features and connect your API to the code translation pipeline you created earlier. As a next step, we'll be putting in practice all the concepts we discussed in this lesson. Keep exploring, and get ready to make your backend even smarter and more powerful!
