REST API for a blog using FastAPI, a modern Python web framework for building APIs.
Step 1: Set Up Your Environment
- Install Python: Ensure Python is installed on your system.
- Install FastAPI and Uvicorn:
pip install fastapi uvicorn
Step 2: Create the FastAPI Application
- Create a new directory for your project:
mkdir fastapi_blog cd fastapi_blog
- Create a file named
main.py
:touch main.py
Step 3: Write the Blog API
In main.py
, write the following code:
Step 4: Run the API
Start the FastAPI server using Uvicorn:
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 curl, Postman, or the built-in Swagger UI provided by FastAPI.
- 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. - Endpoints:
- Create a Post:
POST /posts/
{ "id": 1, "title": "My First Post", "content": "This is my first blog post.", "author": "John Doe" }
- Get All Posts:
GET /posts/
- Get a Single Post:
GET /posts/{post_id}
- Update a Post:
PUT /posts/{post_id}
{ "id": 1, "title": "Updated Post", "content": "This post has been updated.", "author": "John Doe" }
- Delete a Post:
DELETE /posts/{post_id}
- Create a Post:
Step 6: Example Workflow
- Create a Post:
- Send a
POST
request to/posts/
with a JSON body. - Example:
{ "id": 1, "title": "My First Post", "content": "This is my first blog post.", "author": "John Doe" }
- Send a
- Get All Posts:
- Send a
GET
request to/posts/
. - Response:
[ { "id": 1, "title": "My First Post", "content": "This is my first blog post.", "author": "John Doe" } ]
- Send a
- Get a Single Post:
- Send a
GET
request to/posts/1
. - Response:
{ "id": 1, "title": "My First Post", "content": "This is my first blog post.", "author": "John Doe" }
- Send a
- Update a Post:
- Send a
PUT
request to/posts/1
with an updated JSON body. - Example:
{ "id": 1, "title": "Updated Post", "content": "This post has been updated.", "author": "John Doe" }
- Send a
- Delete a Post:
- Send a
DELETE
request to/posts/1
. - Response:
{ "message": "Post deleted successfully" }
- Send a
Step 7: Optional Enhancements
- Persistent Storage: Use a database like SQLite, PostgreSQL, or MongoDB to store posts instead of an in-memory list.
- Authentication: Add user authentication using OAuth2 or JWT.
- Pagination: Implement pagination for the
GET /posts/
endpoint. - Validation: Add more validation for post data (e.g., minimum title length).
- Deployment: Deploy the API to a cloud platform like Heroku, AWS, or Google Cloud.