Setting Up FastAPI: A Beginner’s Guide

FastAPI is a modern, high-performance web framework for building APIs with Python. Here’s how you can get started quickly!

Step 1: Install FastAPI and Uvicorn

FastAPI is the web framework, and Uvicorn is the ASGI server used to run FastAPI applications.

Open your terminal or command prompt and run the following commands:

python -m pip install fastapi
pip install uvicorn

This will install FastAPI and Uvicorn on your system.

Step 2: Create Your First FastAPI Application

Create a Python file named myapi.py and add the following code:

from fastapi import FastAPI, Path
from typing import Optional

app = FastAPI()

students = {
    1: {
        “name”: “john”,
        “age”: 17,
        “class”: “year 12”
    }
}

@app.get(“/”)
def index():
    return {“name”: “First Data”}

@app.get(“/get-student/{student_id}”)
def get_student(student_id: int = Path(…, description=”The ID of the student you want to view”, gt = 0, lt = 3)):
    return students.get(student_id, {“error”: “Student not found”})

@app.get(“/get-by-name/{student_id}”)
def get_student(*, student_id: int, name : Optional[str] = None, test : int):
    for student_id in students:
        if students[student_id][“name”] == name:
            return students[student_id]
    return {“Data”: “Not found”}    

This code creates a FastAPI app with a single route (/) that returns a JSON response with the message "Welcome to FastAPI!".

Step 3: Run Your FastAPI Application

Once your app is ready, you can run it using Uvicorn.

Run the following command in your terminal:

uvicorn myapi:app –reload

  • myapi:app tells Uvicorn to look for the app object in the myapi.py file.
  • --reload enables auto-reloading, so your server will automatically restart whenever you make changes to the code.

After running this command, Uvicorn will start the server, and your FastAPI application will be available at http://127.0.0.1:8000/.

Step 4: Test Your API

Open your browser and go to http://127.0.0.1:8000/. You should see the JSON response:

{
“name”: “First Data”
}

You can also explore FastAPI’s built-in interactive API documentation by visiting:

  • Swagger UI: http://127.0.0.1:8000/docs
  • Redoc UI: http://127.0.0.1:8000/redoc

Conclusion

That’s it! 🎉 You’ve successfully set up a basic FastAPI application. With just a few commands, you’re ready to start building APIs quickly and efficiently.

Stay tuned for more advanced topics in future posts!

Easy Introduction to Chrome Extension.

  1. Create a Folder
    • Name it: DadJokes
    • This folder will hold all the essential files needed for your extension.

  1. Create manifest.json
    • Inside the DadJokes folder, create a new file called manifest.json.
    • The manifest.json file defines the metadata of your extension, such as name, version, permissions, and scripts.

manifest.json content:

{
    “name” : “Dad Jokes”,
    “version” : “0.0.1”,
    “manifest_version” : 3,
    “action”: {
        “default_popup”: “popup.html”,
        “default_icon”: {
          “128”: “logo.png”
        }
    },
    “permissions” : [“activeTab”]
}

3. Create popup.html

  • Next, create another file in the same folder and name it popup.html.
  • This HTML file will serve as the UI that opens when you click on the extension icon in Chrome.

Sample popup.html content:

<!DOCTYPE html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <title>Dad Jokes</title>
</head>
<body>
    <p id=”jokeElement”>Loading…</p>
    <script src=”script.js”></script>
</body>
</html>

4. Add a Logo (logo.png)

  • Create an image file called logo.png inside the DadJokes folder.
  • This will serve as the icon that appears in the Chrome toolbar when your extension is installed.

Note: Make sure the image is in PNG format and follows the size guidelines for Chrome extensions (usually 128×128 pixels).

5. Create script.js

  • Now, create a file named script.js in the DadJokes folder.
  • This JavaScript file will contain the logic to fetch and display a random dad joke.

Sample script.js content:

fetch(‘https://icanhazdadjoke.com/slack’, {
    headers: {
        ‘Accept’: ‘application/json’
    }
})
    .then(response => response.json())
    .then(jokeData => {
        const jokeText = jokeData.attachments[0].text;  // Corrected key ‘attachments’
        const jokeElement = document.getElementById(‘jokeElement’);
        jokeElement.innerHTML = jokeText;
    })
    .catch(error => {
        console.error(‘Error fetching the joke:’, error);
    });
    • Open Chrome, go to chrome://extensions/, and turn on Developer Mode (toggle in the top right).
    • Click Load unpacked and select the DadJokes folder.
    • Your Chrome extension will now be installed and visible in the toolbar!

By following these steps, you’ll have a working Chrome extension that displays a random dad joke whenever you click its icon.