Hello Friends! On day 39, we're going to discuss about building APIs with FastAPI. If you've been following along, you know we've covered a lot of ground, from basic Python scripting to more complex automation tasks. Today, we're shifting gears to explore the powerful capabilities of FastAPI for creating robust APIs.
What's FastAPI?
FastAPI is a modern, fast (hence the name), web framework for building APIs with Python 3.7 and above. It's designed to be easy to use, high-performance, and to generate interactive API documentation automatically. If you're thinking about building APIs for your applications or services, FastAPI is a fantastic choice.
Getting Started
Let's dive into the practical side. First things first, you need to install FastAPI and an additional tool called uvicorn to run the server. Open up your terminal and run:
pip install fastapi uvicorn
Now, imagine you're building an API for a task tracker. You want to create, read, update, and delete tasks. FastAPI makes this process surprisingly simple.
Creating Your First API
Fire up your favorite code editor and create a file, let's call it main.py. Now, let's define a simple API for managing tasks.
from fastapi import FastAPI
app = FastAPI()
tasks = []
@app.get("/tasks")
def get_tasks():
return tasks
@app.post("/tasks")
def create_task(task: str):
tasks.append(task)
return {"message": "Task created successfully"}
Here, we've created a FastAPI instance, defined a list called tasks to store our tasks, and added two endpoints. The get_tasks function handles GET requests to retrieve all tasks, and the create_task function handles POST requests to add a new task.
Running the Server
To see this in action, run the following command in your terminal:
uvicorn main:app --reload
Visit http://127.0.0.1:8000/docs in your browser, and you'll be greeted with an interactive documentation page generated by FastAPI. It's like magic – no manual documentation needed!
Interacting with the API
Now, let's interact with our API using a tool like httpie or curl. In a new terminal window, run the following commands:
# Get all tasks
http get http://127.0.0.1:8000/tasks
# Create a new task
http post http://127.0.0.1:8000/tasks task="Finish blog on FastAPI"
You'll see the responses in the terminal, and if you check the interactive documentation, you'll notice that FastAPI has already documented our API for us!
Adding More Features
FastAPI supports request and response models, dependency injection, and many other advanced features. For instance, you can enhance our API by specifying data types for the request and response.
from pydantic import BaseModel
class Task(BaseModel):
name: str
description: str = None
@app.post("/tasks")
def create_task(task: Task):
tasks.append(task.dict())
return {"message": "Task created successfully"}
Now, each task requires a name, and you can also provide an optional description. FastAPI will automatically validate the incoming data, making your API more robust.
Congratulations! You've just scratched the surface of FastAPI for building APIs in Python. We covered the basics of installation, creating endpoints, and exploring some advanced features.
FastAPI's simplicity and automatic documentation make it an excellent choice for developers looking to create APIs efficiently. As you continue to explore its features, you'll find it to be a powerful tool in your PythonForDevOps journey.
In the next blog, we'll explore more Python tools and techniques for DevOps tasks.
Thank you for reading!
*** Explore | Share | Grow ***
Comments