REST API for a blog using FastAPI, a modern Python web framework for building APIs.

Step 1: Set Up Your Environment

  1. Install Python: Ensure Python is installed on your system.
  2. Install FastAPI and Uvicorn:
    bash
    pip install fastapi uvicorn

Step 2: Create the FastAPI Application

  1. Create a new directory for your project:
    bash
    mkdir fastapi_blog
    cd fastapi_blog
  2. Create a file named main.py:
    bash
    touch main.py

Step 3: Write the Blog API

In main.py, write the following code:

python
Copyfrom fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Optional app = FastAPI() # In-memory “database” for blog posts posts = [] # Model for a blog post class Post(BaseModel): id: int title: str content: str author: str # Helper function to find a post by ID def find_post(post_id: int): for post in posts: if post.id == post_id: return post return None # Create a new post @app.post(“/posts/”, response_model=Post) def create_post(post: Post): posts.append(post) return post # Get all posts @app.get(“/posts/”, response_model=List[Post]) def get_posts(): return posts # Get a single post by ID @app.get(“/posts/{post_id}”, response_model=Post) def get_post(post_id: int): post = find_post(post_id) if post is None: raise HTTPException(status_code=404, detail=“Post not found”) return post # Update a post by ID @app.put(“/posts/{post_id}”, response_model=Post) def update_post(post_id: int, updated_post: Post): post = find_post(post_id) if post is None: raise HTTPException(status_code=404, detail=“Post not found”) post.title = updated_post.title post.content = updated_post.content post.author = updated_post.author return post # Delete a post by ID @app.delete(“/posts/{post_id}”) def delete_post(post_id: int): post = find_post(post_id) if post is None: raise HTTPException(status_code=404, detail=“Post not found”) posts.remove(post) return {“message”: “Post deleted successfully”}

Step 4: Run the API

Start the FastAPI server using Uvicorn:

bash
uvicorn main:app --reload

The --reload flag enables auto-reloading, so the server will restart whenever you make changes to the code.


Step 5: Test the API

You can test the API using curlPostman, or the built-in Swagger UI provided by FastAPI.

  1. Swagger UI: Open your browser and go to http://127.0.0.1:8000/docs. This will display an interactive API documentation where you can test all the endpoints.
  2. Endpoints:
    • Create a PostPOST /posts/
      json
      {
        "id": 1,
        "title": "My First Post",
        "content": "This is my first blog post.",
        "author": "John Doe"
      }
    • Get All PostsGET /posts/
    • Get a Single PostGET /posts/{post_id}
    • Update a PostPUT /posts/{post_id}
      json
      {
        "id": 1,
        "title": "Updated Post",
        "content": "This post has been updated.",
        "author": "John Doe"
      }
    • Delete a PostDELETE /posts/{post_id}

Step 6: Example Workflow

  1. Create a Post:
    • Send a POST request to /posts/ with a JSON body.
    • Example:
      json
      {
        "id": 1,
        "title": "My First Post",
        "content": "This is my first blog post.",
        "author": "John Doe"
      }
  2. Get All Posts:
    • Send a GET request to /posts/.
    • Response:
      json
      [
        {
          "id": 1,
          "title": "My First Post",
          "content": "This is my first blog post.",
          "author": "John Doe"
        }
      ]
  3. Get a Single Post:
    • Send a GET request to /posts/1.
    • Response:
      json
      {
        "id": 1,
        "title": "My First Post",
        "content": "This is my first blog post.",
        "author": "John Doe"
      }
  4. Update a Post:
    • Send a PUT request to /posts/1 with an updated JSON body.
    • Example:
      json
      {
        "id": 1,
        "title": "Updated Post",
        "content": "This post has been updated.",
        "author": "John Doe"
      }
  5. Delete a Post:
    • Send a DELETE request to /posts/1.
    • Response:
      json
      {
        "message": "Post deleted successfully"
      }

Step 7: Optional Enhancements

  1. Persistent Storage: Use a database like SQLitePostgreSQL, or MongoDB to store posts instead of an in-memory list.
  2. Authentication: Add user authentication using OAuth2 or JWT.
  3. Pagination: Implement pagination for the GET /posts/ endpoint.
  4. Validation: Add more validation for post data (e.g., minimum title length).
  5. Deployment: Deploy the API to a cloud platform like HerokuAWS, or Google Cloud.